Home Symphony The simplest blog in Symfony 2

The simplest blog in Symfony 2

by admin

Hello, %username%!
symfony – A popular PHP framework on which more than a few symfony scripts have been built. serious projects But in the Russian-speaking community it is much less common. Whether it’s because of the higher entry threshold, or the lack of Russian-language documentation.
In thisarticle I want to describe how to make a simple blog on symfony2.

Step 0: Software Requirements

Web server (e.g., Apache) with 5.3.2 or higher.
Database server. We will use MySQL.
Git (optional).

Step 1: Installation.

There are two ways : download the archive from the website or use git. We’ll go with the second one, since many bundles are updated following the repository.
At the root of the web server, run the commands :
git clone https://github.com/symfony/symfony-standard.git symfony
cd symfony
php bin/vendors.php

Follow this link http://localhost/symfony/web/config.php This is where symfony will write the requirements and configuration recommendations for the web server.
In my case you just need to specify the date.timezone directive in php.ini.
There, at the bottom of the page says the location of your php.ini.
After you’ve fixed all the problems, the fun part awaits you.
Follow the link, from the same page, http://localhost/symfony/web/app_dev.php/_configurator/
Here you can configure the connection to the database and set the secret key to prevent CSRF attacks.
After that, symfony will be configured, or will prompt you to enter the configuration if the app/config/parameters.ini file is not writable.
It’s worth mentioning the bundles. In this case we will use the AcmeDemoBundle, which is an already built bundle, to create demo applications. I will not go into the bundles, the only thing I will say is that they are the building blocks for your application in symfony2.
We also need another bundle, the FOSUserBundle. It provides everything you need for user interaction – login, registration, password confirmation, and more.
Download :
git submodule add -f git://github.com/FriendsOfSymfony/UserBundle.git vendor/bundles/FOS/UserBundle

Add a newnamespacein app/autoload.php:

$loader->registerNamespaces(array(<br> 'FOS' => __DIR__. '/../vendor/bundles' , <br> // your other namespaces <br>); <br>

We add a new bundle to our app in app/AppKernel.php:

public function registerBundles()<br>{<br> return array(<br> // ... <br> new FOS\UserBundle\FOSUserBundle(), <br> // ... <br>);<br>} <br>

In app/config/security.yml, replace the providers parameter:

security:<br>providers:<br>fos_userbundle:<br>id: fos_user.user_manager <br>

And also change firewalls and access_control to allow anonymous access to all pages except the post creation page.

firewalls:<br>main:<br>pattern: .*<br>form_login:<br> provider: fos_userbundle<br> login_path: /login<br> use_forward: false<br> check_path: /login_check<br> failure_path: null<br> logout: true<br> anonymous: true<br> access_control:<br> - { path: /post/new, role: ROLE_USER } <br> - { path: /.*, roles: IS_AUTHENTICATED_ANONYMOUSLY} <br>

In app/config/config.yml delete auto_mapping: true and add the following :

doctrine:<br> orm:<br> mappings:<br> FOSUserBundle: ~<br> AcmeDemoBundle: ~<br> # your other bundles<br>

and at the end of the file add :

<br> fos_user:<br> db_driver: orm<br> firewall_name: main<br> class:<br> model:<br> user: Acme\DemoBundle\Entity\User <br>

You also need to add to framework translator to enable line translation. Especially the FOSUserBundle strings.

framework:<br> translator: { fallback: en } <br>

Step 2: Create Models.

Create files in the directory src/Acme/DemoBundle/Entity. If you don’t have such a folder, create it.

<?php<br> <br> namespace Acme\DemoBundle\Entity;<br> <br> use Doctrine\ORM\Mapping as ORM;<br> <br> /** <br> * <br> *@ORM\Entity <br> */ <br> class Post<br> {<br> /** <br> *@var integer $id <br> * <br> * @ORM\Id <br> * @ORM\Column(name="id", type="integer") <br> * @ORM\GeneratedValue(strategy="AUTO") <br> */ <br> private $id;<br> <br> /** <br> * @ORM\ManyToOne(targetEntity="User", inversedBy="posts") <br> * @ORM\JoinColumn(name="user_id", referencedColumnName="id") <br> */ <br> public $user;<br> <br> /** <br> * @var string The simplest blog in Symfony 2 <br> * <br> * @ORM\Column(name="title", type="string", length=255) <br> */ <br> public The simplest blog in Symfony 2;<br> <br> /** <br> * @var text $description <br> * <br> * @ORM\Column(name="description", type="text") <br> */ <br> public $description;<br> } <br>

The comments before the variables are annotations. There should be no difficulty in using them, unless, of course, you wonder "how does it work?".

<?php<br> namespace Acme\DemoBundle\Entity;<br> use FOS\UserBundle\Entity\User as BaseUser;<br> use Doctrine\ORM\Mapping as ORM;<br> <br> /** <br> * @ORM\Entity <br> * @ORM\Table(name="fos_user") <br> */ <br> class User extends BaseUser<br> {<br> /** <br> * @ORM\Id <br> * @ORM\Column(type="integer") <br> * @ORM\generatedValue(strategy="AUTO") <br> */ <br> protected $id;<br> <br> /** <br> * @ORM\OneToMany(targetEntity="Post", mappedBy="fos_user") <br> */ <br> public $posts;<br> <br> public function __construct()<br> {<br> parent::__construct();<br> // your own logic <br> }<br> } <br>

We inherit from FOS\UserBundle\Entity\User, so in addition to the two fields we set, several more fields will be generated, including username, password and email.
After we write the models we can create the tables :
php app/console doctrine:schema:create

Step 3: Create a controller.

Create a file PostController.php in the src/Acme/DemoBundle/Controller/ folder:

<?php<br> namespace Acme\DemoBundle\Controller;<br> <br> use Symfony\Bundle\FrameworkBundle\Controller\Controller;<br> use Acme\DemoBundle\Entity\Post;<br> use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;<br> <br> class PostController extends Controller<br> {<br> /** <br> * @Template() <br> */ <br> public function indexAction()<br> {<br> $em = $ this -> get ( 'doctrine' )-> getEntityManager();<br> $posts = $em-> getRepository( 'AcmeDemoBundle:Post' )-> findAll();<br> return array( 'posts' => $posts);<br> }<br> <br> /** <br> * @Template() <br> */ <br> public function newAction()<br>{<br>$post = new Post();<br> // We get the user and assign it to a new post <br>$post->user = $ this -> get ( 'security.context' )->getToken()->getUser();<br> // Creating a form, it would be nice to create a separate class, but you can do it like this <br> $form= $ this -> get ( 'form.factory' )<br> -> createBuilder( 'form' , $post)<br> -> add( 'title' , 'text' )<br> -> add( 'description' , 'textarea' )<br> -> getForm();<br>$request = $ this -> get ( 'request' );<br> if ($request-> getMethod() == 'POST' ) {<br> $form-> bindRequest($request);<br> if ($form-> isValid()) {<br> $em = $ this -> get ( 'doctrine' )-> getEntityManager();<br> $em-> persist($post);<br> $em-> flush();<br> return $ this -> redirect($ this -> generateUrl( 'post_index' ));<br> }<br> }<br> return array( 'form' => $form-> createView());<br> }<br> } <br>

Why do you need Template () before every action? Without it instead of
return array('posts' => $posts);

we would have to write
return $this-> render('AcmeDemoBundle:post:index.html.twig', array('posts' => $posts))

Step 4. Templates.

In src/Acme/DemoBundle/Resources/views/Post, create aview for each action.

{% extends 'AcmeDemoBundle::layout.html.twig' %}<br> <br>{% block content %}<br> <br> {% if is_granted('ROLE_USER') %}<br> < div > < a href ="{{ path(" post_new ") }}" > New Post </ a > </ div > <br> {% endif %}<br> <br> {% for post in posts %}<br> < h2 > {{ post.title}} </ h2 > <br> < p > {{ post.description }} </ p > <br> < div > by {{ post.user.username }} </ div > <br> {%else %}<br> There are no articles in the blog yet.<br> {% endfor %}<br> <br> {% endblock %} <br>


{% extends 'AcmeDemoBundle::layout.html.twig' %}<br> <br> {% block content %}<br> < h1 > New Post </ h1 > <br> <br> < form action ="{{ path(" post_new ") }}" method ="post" > <br> {{ form_widget(form) }}<br> <br> < input type ="submit" class ="symfony-button-grey" value ="Create" /> <br> </ form > <br> {% endblock %} <br>

About the Twig templating tool already in part mentioned on the hubra , but there is also a excellent official documentation , although in English.

Step 5. Routes.

In app/config/routing.yml we write our Routes and don’t forget about UserBundle

post_index:<br> pattern: /post<br> defaults: { _controller: AcmeDemoBundle:Post:index }<br> <br> post_new:<br> pattern: /post/new<br> defaults: { _controller: AcmeDemoBundle:Post:new }<br> <br> fos_user_security:<br> resource: "@FOSUserBundle/Resources/config/routing/security.xml"<br> <br> fos_user_user:<br> resource: "@FOSUserBundle/Resources/config/routing/user.xml"<br> prefix: /user <br> <br> * This source code was highlighted with Source Code Highlighter

Our blog will now be available at http://localhost/symfony/web/app_dev.php/post , and when you try to go to http://localhost/symfony/web/app_dev.php/post/new you will be redirected to the login page.


I don’t claim to be a complete guide or originality, this is more of a quick-start note on the application for myself.
I will be glad if someone can use it, also do not refuse help and criticism.
If you have any questions, feel free to ask, I think there are people on hubra who are working on this framework.
We also have a jabber conference symfony@conference.jabber.ru

You may also like