📜 ⬆️ ⬇️

The simplest blog on symfony 2

Hi% username%!
symfony is a popular PHP framework, on which quite a few serious projects have been created . But in the Russian-speaking community, it is much less common. Whether this is due to a higher threshold of entry, or the lack of Russian-language documentation.
In this article I want to talk about creating a simple blog on symfony2.

Step 0. Software Requirements

Web server (for example, Apache) from 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 site or use git. We will go to the second, because many bundles are updated following the repository.
At the root of the web server, execute the following commands:
git clone https://github.com/symfony/symfony-standard.git symfony
cd symfony
php bin/vendors.php

Follow the link http: //localhost/symfony/web/config.php . Here symfony will write requirements and recommendations for setting up a web server.
In my case, you only need to specify the date.timezone directive in php.ini.
There, at the bottom of the page is written the location of your php.ini.
After you fix all the problems, you will find the most interesting.
Follow the link from the same page, http: //localhost/symfony/web/app_dev.php/_configurator/ .
Here you can set up a connection to the database and set a secret key to prevent a CSRF attack.
After that, symfony will be configured, or it will prompt you to enter the resulting configuration itself, if the app / config / parameters.ini file is not writable.
Here it is worth mentioning the bundles. In this case, we will use AcmeDemoBundle - already created bundle to create demo applications. I will not go into the bundles, I will only say that in symfony2 of them, like from bricks, your application is built.
We also need another bundle - FOSUserBundle. It provides everything you need to work with users - login, registration, password confirmation and more.
Download:
git submodule add -f git://github.com/FriendsOfSymfony/UserBundle.git vendor/bundles/FOS/UserBundle

Add a new namespace (namespace) in app / autoload.php:
$loader->registerNamespaces(array(<br> 'FOS' => __DIR__. '/../vendor/bundles' ,<br> // your other namespaces <br>); <br>

Add a new bundle to our application in the file 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 we also change the firewalls and access_control to allow anonymous access for all pages, except for the message 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, remove 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 we 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 it to the framework translator to enable the translation of strings. In particular, the FOSUserBundle lines.
framework:<br> translator: { fallback: en } <br>

Step 2. Creating models.

Create files in the src / Acme / DemoBundle / Entity directory. If there is no such folder, create it.
Post.php:
<?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 $title <br> * <br> * @ORM\Column(name="title", type="string", length=255) <br> */ <br> public $title;<br><br> /** <br> * @var text $description <br> * <br> * @ORM\Column(name="description", type="text") <br> */ <br> public $description;<br>} <br>

Comments before variables - annotations. There should be no difficulties in their use, unless, of course, one wonders “how does it work?”.
User.php:
<?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 that in addition to the two fields that we specified, several more fields will be generated, including username, password and email.
After writing the models, we can safely create the tables:
php app/console doctrine:schema:create

Step 3. Creating a controller.

Create a PostController.php file 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> // <br> $post->user = $ this -> get ( 'security.context' )->getToken()->getUser();<br> // , , <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 I need Template () before each action? Without him instead
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 we will create a view for each action.
index.html.twig:
{% 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> .<br>{% endfor %}<br><br>{% endblock %} <br>

new.html.twig:
{% 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 template engine is already partially mentioned in Habré , but there is also excellent official documentation , though in English.
Step 5. Routes.

In app / config / routing.yml we register our routes and do not 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 .

Now our blog will be available via the link 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 page the entrance.
Afterword

I do not pretend to be a complete guide and originality, it is rather a quick start note for an application for myself.
I would be happy if someone come in handy, just do not give up help and criticism.
Who will have questions - ask, I think on Habré there are people who are engaged in this framework.
In addition, we have a jabber conference symfony@conference.jabber.ru

')

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


All Articles