Question

i'm new here and i hope my question is not too trivial.

I have a package with a static class in it (a Grid Builder) and want to use it in symfony2

So i know about the Class loading and the Service Container but i don't get the Container to work.

The Grid Class is depending on 2 other static classes (one for configuration and one for the SQL Query´s)

The Code to use the class is as following:

$Grid = Grid::get_instance();
$Grid->table('products');
echo $Grid->renderGrid();

And internally the class uses calls like GridConfig::database() - so i Thought maybe i cann simply add all three classes to the Service.yml but that doesn't do anything.

So my question is: How can I inject the Static class in a way that I can use it in the Controller? Is it Possible and if yes what would be the best Practice case to do it?

Thank you for any help.

Was it helpful?

Solution

Since it is static then there really is no need to inject it. Something like:

$grid = \Grid::get_instance;

Should work. If Grid uses namespaces then you need to add that as well. And you will need to ensure the autoloader can find it.

Of course using globals is kind of frowned up. What you can do is to write your own service to act as a wrapper.

class MyGridService 
{
    protected $grid;

    public function getInstance()
    {
        if (!$this->grid) $this->grid = \Grid::get_instance();
        return $this->grid;
    }
}

Add MyGridService to your services.yml file then from the controller you can do:

$grid = $this->get('my_grid_service')->getInstance();

OTHER TIPS

You should define a service that uses a factory method to instantiate the object:

service_name:
    class: The\Class\Name\Of\The\Created\Object
    factory: [ "Grid", "get_instance" ]

Now you can inject the object into your depending class by injecting the service.

See http://symfony.com/doc/current/components/dependency_injection/factories.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top