Roman Newaza
Roman Newaza

Reputation: 11690

Making an Object accessible in a controllers which was set in kernel.controller Event

How can make an Object accessible in a controllers which was set in kernel.controller Event?

I have a onKernelController method which is run before controller and I need some data in a controller which was set in onKernelController.

Upvotes: 0

Views: 209

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

You can use dependency injection to solve this:

1) Turn your object/class into a service and inject it into the listener.

services:
    your_object:
        class: Your\Namespace\YourObjectClass

    your_listener:
        class: Your\Namespace\YourListener
        arguments: [ @your_object ]
        tags:      
            - { name: kernel.controller, event: kernel.request, method: onKernelController }

2) Set some property (can be an object aswell) on the injected object

listener class

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class YourListener
{
    protected $object;

    public function __construct($object)
    {
         $this->object = $object;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        // ...

        $object->setProperty('some_property_value');
    }
}

3.) Get the property inside a container-aware controller (or turn your controller into a service aswell and inject @your_object )

controller

use Symfony\Component\DependencyInjection\ContainerAware;
// or: use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SomeController extends ContainerAware // or: extends Controller
{

    public function someAction()
    {
        $property = $this->container->get('your_object')->getProperty; 
        // $property => 'some_property_value'
    }

Upvotes: 2

Related Questions