Download presentation
Presentation is loading. Please wait.
Published byGerald Walker Modified over 6 years ago
1
Symfony Console Services Events Session Georgi Gyurov Symfony
Software University
2
Last time Twig Entities Doctrine, Annotations Validation, Forms
3
Table of contents Console commands Services Events Session
4
Have a question? #sli.do #softuni-symfony
5
Console Eases the creation of beautiful and testable command line interfaces. Used by many projects: The Console component allows you to create command-line commands. Your console commands can be used for any recurring task, such as cronjobs, imports, or other batch jobs. Commands are defined in classes which must be created in the Command namespace of your bundle (e.g. AppBundle\Command) and their names must end with the Command suffix. 5
6
Creating command namespace SoftuniBlogBundle\Command;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; class CreatePostCommand extends Command { protected function configure() // Used for configure command } protected function execute(InputInterface $input, OutputInterface $output) // Execution code 6
7
Creating command - configure
protected function configure() { $this // the name of the command (the part after "bin/console") ->setName('app:create-user') // the short description shown while running "php bin/console list" ->setDescription('Creates a new user.') // the full command description shown when running the command with // the "--help" option ->setHelp('This command allows you to create a user...') ; } 7
8
Creating command - configure
protected function configure() { $this ->setName('app:create-user') ->setDescription('Creates a new user.') ->setHelp('This command allows you to create a user…') ->addArgument('title', InputArgument::REQUIRED, 'Title of post') ->addArgument('description', InputArgument::OPTIONAL, 'Description of post') ->addOption( 'author', 'a', InputOption::VALUE_REQUIRED, 'Author first name' ); ; } Arguments are required and have to be ordered Options are not ordered and specified with two dashes (e.g. --author) Option is optional, but option value can still be required if it is used 8
9
Creating command - execute
protected function execute(InputInterface $input, OutputInterface $output) { //Reading arguments $postTitle = $input->getArgument('title'); $postDescription = $input→getArgument('description'); //Reading options $authorName = $input→getOption('author'); } Console Input (Arguments & Options) - 9
10
Prevent Multiple Executions
Symfony\Component\Console\Command\LockableTrait; Class CreatePostCommand extends Command { Use LockableTrait; protected function execute(InputInterface $input, OutputInterface $output) if (!$this->lock()) { $output->writeln('The command is already running in another process.'); return 0; } 10
11
Logging in Console Commands
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Psr\Log\LoggerInterface; class CreatePostCommand extends ContainerAwareCommand { protected function execute(InputInterface $input, OutputInterface $output) $logger = $this->getContainer()->get('logger'); $logger→addInfo('Start creating post! '); } 11
12
Symfony Services In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. If you have the service container, then you can fetch a service. Your application is full of useful objects: a "Mailer" object might help you send s while another object might help you save things to the database. Almost everything that your app "does" is actually done by one of these objects. And each time you install a new bundle, you get access to even more! The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast! The moment you start a Symfony app, your container already contains many services. These are like tools: waiting for you to take advantage of them. In your controller, you can "ask" for a service from the container by type-hinting an argument with the service's class or interface name. The container is lazy: it doesn't instantiate a service until (and unless) you ask for it. 12
13
Service with type-hinting
use Doctrine\ORM\EntityManagerInterface; /** */ public function listAction(EntityManagerInterface $em) { $em->getRepository("SoftuniBlogBundle:Post"); // ... } !!! The ability to type-hint a service in order to receive it was added in Symfony 3.3 13
14
Fetching services /** */ public function listAction(Post $post) { $em = $this->get('doctrine.orm.entity_manager'); $post→setTitle('test title'); $em->flush(); // ... } Available services can be find with “php bin/console debug:container” command from console. Fetching a service directly from the container like this only works if you extend the Controller class 14
15
Service configuration
parameters: softunibundle.entity.post: "Softuni\BlogBundle\Entity\Post" softuni.blog.post_manager: class: Softuni\BlogBundle\Services\PostManager arguments: entityManager: class: %softunibundle.entity.post% serviceContainer: Arguments can be services, parameters, strings. We can define parameters under parameters section and use it 15
16
Symfony Events During the execution of a Symfony application, lots of event notifications are triggered. Your application can listen to these notifications and respond to them by executing any piece of code. Internal events provided by Symfony itself are defined in the KernelEvents class. Third-party bundles and libraries also trigger lots of events and your own application can trigger custom events. The EventDispatcher component provides tools that allow your application components to communicate with each other by dispatching events and listening to them. Naming Conventions¶ The unique event name can be any string, but optionally follows a few simple naming conventions: Use only lowercase letters, numbers, dots (.) and underscores (_); Prefix names with a namespace followed by a dot (e.g. order., user.*); End names with a verb that indicates what action has been taken (e.g. order.placed). 16
17
Symfony creating event
namespace Softunu\BlogBundle\Event; use Symfony\Component\EventDispatcher\Event; class PostCreationEvent extends Event { /** SoftuniBlogBundle\Enitity\Post */ private $data; public function __construct($data) $this→data = $data; } public function getData() return $this->data; 17
18
Symfony creating event
namespace Softunu\BlogBundle\Event; use Symfony\Component\EventDispatcher\Event; class PostCreationEvent extends Event { public function getNumberOfPosts() return $this→getData()→getAuthor()→getNumberOfPosts(); } 18
19
Symfony dispatch event
/** */ public function viewAction(Post $post) { //Do something with post …. $dispatcher = $this->get('event_dispatcher'); $event = new \Softunu\BlogBundle\Event\PostCreationEvent($post); $dispatcher->dispatch('softuni.author.created', $event); } 19
20
Symfony create event listener
class PostCreationListener { public function onCreatePost(\Softuni\BlogBundle\Event\PostCreateEvent $event) $post = $event->getData(); $author = $even->getAuthor(); $numberOfPosts = $event→getNumberOfPosts(); $author→setNumberOfPosts($numberOfPosts); } 20
21
Symfony register event listener
parameters: softuni_blog.event_listener.class: Softuni\BlogBundle\EventListener\PostCreationListener: services: softuni_blog.event_listener.post_create: class: %softuni_blog.event_listener.class% tags: - { name: kernel.event_listener, event: softuni.author.created, method: onCreatePost } arguments: 21
22
Symfony Session The Symfony HttpFoundation component has a very powerful and flexible session subsystem which is designed to provide session management through a simple object-oriented interface using a variety of session storage drivers. Symfony sessions are designed to replace several native PHP functions. Applications should avoid using session_start(), session_regenerate_id(), session_id(), session_name(), and session_destroy() Symfony sessions are incompatible with php.ini directive session.auto_start = 1 This directive should be turned off in php.ini, in the webserver directives or in .htaccess. PHP's session management requires the use of the $_SESSION super-global, however, this interferes somewhat with encapsulation in an OOP paradigm. To help overcome this, Symfony uses session bags linked to the session to encapsulate a specific dataset of attributes or flash messages. Useful link: 22
23
Symfony Session Attributes
The purpose of the bags implementing the AttributeBagInterface is to handle session attribute storage. This might include things like user ID, and remember me login settings or other user based state information. This way you can easily access a key within the stored array directly and easily. set() Sets an attribute by key. get() Gets an attribute by key. all() Gets all attributes as an array of key => value. has() Returns true if the attribute exists. remove() Deletes an attribute by key. clear() Clear the bag. 23
24
Symfony Flash messages
The usual workflow would be to set flash messages in a request and to display them after a page redirect. For example, a user submits a form which hits an update controller, and after processing the controller redirects the page to either the updated page or an error page. Flash messages set in the previous page request would be displayed immediately on the subsequent page load for that session. add() Adds a flash message to the stack of specified type. get() Gets flashes by type and clears those flashes from the bag. all() Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag. has() Returns true if the type exists, false if not. keys() Returns an array of the stored flash types. clear() Clears the bag. 24
25
https://softuni.bg/courses/
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license. 25
26
Trainings @ Software University (SoftUni)
Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University Foundation softuni.org Software Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license. 26
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.