alexdodonov / mezon-router

Small and fast router
https://twitter.com/mezonphp
267 stars 18 forks source link

How to implement dependency injection #34

Closed simp-lee closed 2 years ago

simp-lee commented 2 years ago

Hi, thanks for your good job.

I want to get the data submitted by POST request, and I use Symfony\Component\HttpFoundation.

How to inject Symfony\Component\HttpFoundation into my controller?

Could you please show me some examples?

router.php

$router->addRoute('/article/update/[i:id]', [new ArticleController(), 'update'], 'POST');
$router->callRoute($_SERVER['REQUEST_URI']);

App\Admin\Controllers:

class ArticleController extends BaseController
{
    public function update ($route, $params, Request $request): string
    {
        $id = $params['id'];
        $request->get('articleData');
        do update ...
    }

}
alexdodonov commented 2 years ago

Hi! I think that using middleware will be the best solution for your task:

// somewhere among other controllers:
class ArticleController extends BaseController
{
    public function update (Request $request): string
    {
        $id = $params['id'];
        $request->get('articleData');
        // do update ...
    }
}

// create router
$router = new  Router();

// register middleware for all routes
$router->registerMiddleware('*', function (string $route, array $parameters){
    return [Request::createFromGlobals()];    
});

// additing routes
$router->addRoute('/article/update/[i:id]', [new ArticleController(), 'update'], 'POST');

// calling route
$router->callRoute($_SERVER['REQUEST_URI']);

Hope this this answer is worth of your star for repo )

simp-lee commented 2 years ago

Yes, star is of course : )

But I still need help. How to get the parameter ID which was defined in the addRoute() method?

// somewhere among other controllers:
class ArticleController extends BaseController
{
    public function update (Request $request): string
    {
        $id = $params['id']; // Obviously not
        $request->get('articleData');
        // do update ...
    }
}
alexdodonov commented 2 years ago

Then try this:

// somewhere among other controllers:
class ArticleController extends BaseController
{
    public function update (Request $request, $parameters): string
    {
        $id = $parameters['id'];
        $request->get('articleData');
        // do update ...
    }
}

// register middleware for all routes
$router->registerMiddleware('*', function (string $route, array $parameters){
    return [
        Request::createFromGlobals(), $parameters
    ];
});
simp-lee commented 2 years ago

Hey Alex,

Thanks for your quick answer, I got your point, and she works fine now.

alexdodonov commented 2 years ago

You are welcome )