M
M
Mariik2015-07-06 22:50:56
PHP
Mariik, 2015-07-06 22:50:56

Silex DI for controller?

Hello.
Is it possible for the controller to accept an object of the Silex\Application class in the constructor?
Tried this approach

$app->get('/','AppComponents\Controllers\HelloController::index' );

// HelloController.php

namespace AppComponents\Controllers;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Silex;
use Silex\Application;

class HelloController{
    
    protected $app; 

    function __construct(Application $app) {
        $this->app = $app;
    }
    
    
    function index() {
        return  new Response("hello");
    }
    
}

As a result, I get an error
At the same time, if the Application object accepts not a constructor, but a class method, then everything works
public function test(Application $app){
     var_dump($app);
     return "Bloody Hell!! Its working";
}

Of course, you can register a class as a service, but it somehow sounds wild.
There is a variant to force sylex to stick Application in the constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-07-06
Protko @Fesor

class as a service, but it somehow sounds wild.

Why? More wildly sounds an injection of the container in a class.
silex.sensiolabs.org/doc/providers/service_control...
again, follow the link to learn how to inject anything into the controller class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question