⬆️ ⬇️

Introduction to symfony 2

The release of symfony 2 seemed like a good enough reason to finally find the time and see what one of the most popular PHP frameworks in the world is. I described my acquaintance with him in this article. Since this is my first experience with symfony, I will be glad if you notice any mistakes or shortcomings and let me know about them.



1. Installation and configuration



You can download the distribution from the official site . I think it is better to download the version-standart that comes with all the additional components. Further, I assume that the archive was unpacked into the root folder of your web server.

Check that everything works correctly on this link: http: //localhost/Symfony/web/config.php .

If everything is fine, then you can start, but first you need to comment out one line in the symfony / web / app_dev.php file



$kernel->loadClassCache();



A very strange solution, by default, enable the cache in development mode.



2. Creating a new application



')

Applications in symfony 2 have a modular structure, the modules are called bundles. Our demo application will be in its separate bundle. There are a lot of console commands in symfony that will help you in your work. There is a corresponding command for generating the structure of the new bundle:



php app/console generate:bundle --namespace=Demos/BlogBundle



This command needs to be executed from the console, being in the Symfony / folder. If you are working in Linux, you can assign the console file permissions to execute and not write php in front of it. The generator will ask a few simple questions for each of which it has a default answer. Since we are creating our first application, we agree on all options. So, pressing the enter key several times will get the skeleton of our bundle in the symfony / src / Demos / BlogBundle folder.



3. The controller and the basics of routing



Like most modern frameworks, symfony follows the MVC pattern. We will begin our acquaintance with the implementation of this pattern in symfony with the last letter, i.e. controller.

Our little bundle already has one controller, it is called DefaultController and is located in the src / Demos / BlogBundle / Controller folder. If you look inside of him, you will see that he has an indexAction action. Now we will see what he does. Open the address http: //localhost/Symfony/web/app_dev.php/hello/username in your browser.

You may wonder why this is exactly the address of this page, but if you look closely at PHPDoc (these are special comments that start with / ** characters) before the indexAction function, you will probably understand everything. Route annotation indicates to which address this action is available and which parameter it has.

In general, the same can be achieved without annotations, but they are used everywhere in symfony, so it's best to get used to them right away. On the one hand, they are more concise, and on the other hand, autocomplete in my favorite IDE is not well supported for them.

A special component of Routing is responsible for setting up how the urls of your application will look, it allows you to customize everything very flexibly. More details can be found in the corresponding section of the documentation . We will briefly consider why our application opens precisely at this address and why it was not necessary for us to set anything up for this.

If you didn’t read very carefully what the bundle generator asked you, you could easily have missed asking whether to update the routing settings in accordance with the new bundle. If you missed, you can open the Symfony \ app \ config \ routing.yml file. There you will see the following entry:



DemosBlogBundle:

resource: "@DemosBlogBundle/Controller/"

type: annotation

prefix: /



The first line is the name of the section with the configuration, it corresponds to the name of our bundle. The second line indicates where to import the settings. In this case, they will read all the files from the folder with the controllers, and the next line says that all the necessary settings are described in the action annotations. Well, we have already seen the annotations. And finally, the last line indicates which prefix will be added to all URLs from our bundle. By default, all URLs are accessible directly from the input script. Let's change / to / blog to make it more logical.

Now everything we will do will be available at http: //localhost/Symfony/web/app_dev.php/blog .



4. Working with Doctrine: creating a model



We now turn to the next step - working with the database. I will use Doctrine, although no one is obliged to do this, instead of doctrine, you can use any way you like to work with DB. However, the doctrine is well integrated with symfony and it is a pleasure to work with it.

To begin, set up a connection to the database. Open the file app / config / parameters.ini and describe your settings. By the way, I wonder why all the settings are defaulted in yml, and this one in the ini-file. If you specified a non-existing database in the settings, then run the following command:

php app / console doctrine: database: create

and the doctrine itself will create it.

The doctrine is a full-fledged ORM , but it is postponed by another principle than ActiveRecord , with which many now unambiguously associate this concept. The doctrine implements the Data Mapper template, which is very detailed here .

First we need to describe the entity with which we will work. This will be a Post class with the properties we need. Create a folder src / Demos / BlogBundle / Entity. In it, create a Post.php file and fill it with the following code:



<?php

namespace Demos\BlogBundle\Entity;



use Doctrine\ORM\Mapping as ORM;



/**

* @ORM\Entity

* @ORM\Table(name="post")

*/

class Post {



/**

* @ORM\Id

* @ORM\Column(type="integer")

* @ORM\GeneratedValue(strategy="AUTO")

*/

protected $id;



/**

* @ORM\Column(type="string", length=255)

*/

protected $title;



/**

* @ORM\Column(type="text")

*/

protected $body;



/**

* @ORM\Column(type="datetime")

*/

protected $created_date;



/**

* @ORM\Column(type="datetime")

*/

protected $updated_date;

}




The class itself is in no way associated with the database, but the annotations contain a description of which of the class properties will be columns of the table and what type they will be. I think from the annotations everything is quite obvious. All properties are declared protected, so you must create getters and setters to access them. For this we use the appropriate command of the doctrine:



php app/console doctrine:generate:entities Demos/BlogBundle/Entity/Post



Now look at the Post.php file, it should have appeared appropriate methods. We have a description of the model, for it you need to create the appropriate table in the database. To do this, run:



php app/console doctrine:schema:update --force



If everything went without errors, then the post table should appear in your database. Let's move on to working directly with objects. In the DefaultController class, create a new action with this code:



/**

* @Route("/create")

*/

public function createAction() {

$post = new Post();

$post->setTitle('Demo Blog');

$post->setBody('Hello Symfony 2');

$post->setCreatedDate(new \DateTime("now"));

$post->setUpdatedDate(new \DateTime('now'));



$em = $this->getDoctrine()->getEntityManager();

$em->persist($post);

$em->flush();



return new Response('Created product id ' . $post->getId());

}





And at the beginning of the file you need to add the import of the necessary namespaces:



use Demos\BlogBundle\Entity\Post;

use Symfony\Component\HttpFoundation\Response;




Now, if you open the address http: //localhost/Symfony/web/app_dev.php/blog/create , then you should receive the id of the created entry in response.

Now create an action to display the existing records. For this we need an action with a parameter that will take the id of the record.



<?php

/**

* @Route("/show/{id}")

*/

public function showAction($id)

{

$post = $this->getDoctrine()->getRepository('DemosBlogBundle:Post')->find($id);



if (!$post) {

throw $this->createNotFoundException(' !');

}



$html = <<<HTML

<h1>{$post->getTitle()}</h1>



<p>{$post->getBody()}</p>



<hr/>

<small> {$post->getCreatedDate()->format("Ymd H:i:s")}</small>

HTML;



return new Response($html);

}

?>





Now you can view the record by following the link http: //localhost/Symfony/web/app_dev.php/blog/show/1 . On this doctrine is complete, the details in the documentation .



5. Twig: first patterns



It's time to move on to the final part of our acquaintance with symfony. At the last step, we didn’t do well by mixing the logic of working with the output of a record in showAction. The View will help us to get rid of this drawback (in Russian, the “look” doesn’t sound very good, so I’ll call it a view;).

Symfony uses Twig as a template engine, perhaps the best PHP template engine I've worked with. Like any other component of a symphony, you can replace it with something you like.

As you remember, the indexAction action has a special annotation, Template (), which says that it has a template.



return array('name' => $name);



The array that is returned from the action is passed to the view, the array keys will be the names of the variables that will be available there.

Let's change the show action. You need to add the corresponding annotation and instead of returning the Response object to return an array in which the record will be viewed. Here's what happened:



/**

* @Route("/show/{id}")

* @Template()

*/

public function showAction($id)

{

$post = $this->getDoctrine()->getRepository('DemosBlogBundle:Post')->find($id);



if (!$post) {

throw $this->createNotFoundException(' !');

}



return array('post' => $post);

}




Agree, so much better. Now in the src / Demos / BlogBundle / Resources / views / Default folder create a show.html.twig file into which you transfer the html code that we had to the action movie. The syntax of a twig is different from php, so you have to change something. The final version, see the source. You can learn more about syntax tvig in its documentation .



6. Conclusion



Perhaps this will stop. I hope someone else besides me will be interested. At the beginning, it was a bit tricky to work with symfony, but still interesting. All sources are available on github .

Source: https://habr.com/ru/post/125469/



All Articles