Service in symfony2 - what should a service file look like?

I am trying to create a service in symfony2 that will check if the session contains certain information and if it does not redirect the user to another controller. I want this piece of code to work as a service, as I will use it in many controllers.

I have a problem because the Symfony2 book guide does not contain information about what the service file should look like. Should it be a normal php class?

Below you can find a dump of my files with the error information I get.

In \AppBundle\Services create a file my_isbookchosencheck.php containing:

 <?php namespace AppBundle\my_isbookchosencheck; class my_isbookchosencheck { public function __construct(); { $session = new Session(); $session->getFlashBag()->add('msg', 'No book choosen. Redirected to proper form'); if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks')); } } 

My service.yml :

 my_isbookchosencheck: class: AppBundle\Services\my_isbookchosencheck 

My conntroller file:

 /** * This code is aimed at checking if the book is choseen and therefore whether any further works may be carried out */ $checker = $this->get('my_isbookchosencheck'); 

Mistake:

 FileLoaderLoadException in FileLoader.php line 125: There is no extension able to load the configuration for "my_isbookchosencheck" (in C:/wamp/www/symfony_learn/app/config\services.yml). Looked for namespace "my_isbookchosencheck", found "framework", "security", "twig", "monolog", "swiftmailer", "assetic", "doctrine", "sensio_framework_extra", "fos_user", "knp_paginator", "genemu_form", "debug", "acme_demo", "web_profiler", "sensio_distribution" in C:/wamp/www/symfony_learn/app/config\services.yml (which is being imported from "C:/wamp/www/symfony_learn/app/config\config.yml"). 
0
source share
3 answers

There are a few mistakes you made that I will explain briefly, and I will give you an example of the service you want to create.

  • You created your service in AppBundle\Services , but your namespace is registered differently - namespace AppBundle\Services\my_isbookchosencheck; . This should be namespace AppBundle\Services; . I would also recommend using unique names when creating directories - in this case, Service would be better than Services .

  • You use your __constructor directly to apply some logic and return the result. It would be best to create a custom method that could be accessed when necessary.

  • You create a new instance of Session , which means that you cannot access anything that was previously added and saved in the session. The correct way here is to enter a RequestStack that contains the current Request and get the session from there.

  • I believe that you also incorrectly registered your service. In your services.yml file, it should be under services: This is why you got the error you attached.

So, let's see how you like your service.

services.yml

 services: book_service: class: AppBundle\Service\BookService arguments: - @request_stack - @router 

BookService.php

 namespace AppBundle\Service; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Routing\RouterInterface; class BookService { /* @var $request Request */ private $request; /* @var $router RouterInterface */ private $router; public function __construct(RequestStack $requestStack, RouterInterface $router) { $this->request = $requestStack->getCurrentRequest(); $this->router = $router; } public function isBookChoosen() { $session = $this->request->getSession(); // Now you can access session the proper way. // If anything was added in session from your controller // you can access it here as well. // Apply your logic here and use $this->router->generate() } } 

Now in your controller you can simply use it as follows:

 $this->get('book_service')->isBookChoosen() 

Ok, this is a short example, but I hope you have an idea.

+1
source

to try

 services: my_isbookchosencheck: class: AppBundle\Services\my_isbookchosencheck 

in your service.yml and make sure you use the correct namespaces.

Your class is fine, and it should work, however I can assume that you are using symfony2 session service instead of creating a session object yourself, you can pass it as a constructor argument:

 <?php // namespace edited namespace AppBundle\Services; use Symfony\Component\HttpFoundation\Session\Session; class my_isbookchosencheck { public function __construct(Session $session); { $session->getFlashBag()->add('msg', 'No book choosen. Redirected to proper form'); if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks')); } } 

and then edit your services.yml accordingly, so the service container will enter the session object:

 services: my_isbookchosencheck: class: AppBundle\Services\my_isbookchosencheck arguments: [@session] 

Also check out his question: How do I access a user session from a service in Symfony2?

+1
source

Services are just ordinary PHP classes, nothing special. But you must register it for the system to recognize. Here are the steps how you do it,

Create a regular PHP class (you can introduce other services if required)

 namespace Acme\DemoBundle\Service; class MyService { private $session; public function _construct(SessionInterface $session /* here we're injecting the session service which implements the SessionInterface */) { $this->session = $session; } // other methods go here, which holds the business logic of this class } 

ok, we created a class, we need to register it in order to use it in the container service, here is how you do it:

The easiest way is to put it in the config.yml file, for example:

 services: my_service: class: Acme\DemoBundle\Service\MyService arguments: - @session 

or, otherwise, create a file (for example, services.yml , can be located in the config folder) and import it inside the config.yml file (the contents of the file coincide with the first method):

 imports: - { resource: services.yml } 

or you can create a services.yml file (the contents of the file matches the first method) inside the bundle Resources folder, specify it in accordance with the load method of your extension class (in accordance with DependencyInjection), (this requires a special directory and file structure, read about this in the document) :

 class AcmeDemoExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources')); $loader->load('services.yml'); } } 

In your case, you are not registering your service, the service container simply could not find it. Register it using one of the following methods.

+1
source

All Articles