Micro application finish method


Is it possible to pass object to finish method of Micro app.

Let's say , we have this POST method

$app->post("/wsd" ,  function() use($app){

   $car= new Car();
   //===> I want to send $car to finish method.

And Here my finish method

 function () use ($app) {
if($app->getRouter()->getMatchedRoute() != null ){            
     $route_name =  $app->getRouter()->getMatchedRoute()->getName();      
    if($route_name == "createCar" ||  ){
             // I want to get my car object here.

Thanks for your answer !


edited Dec '16

Just pass car object to the DI ($di->setShared("myCar", new Car());) and get it anywhere from DI ($car = $di->getShared("myCar");)

Thanks Seghei, for your solution.

As DI is used to share objects for all users, in terms of design (and maby performance) , is it good solution? Because each car will be create for each request.

edited Dec '16

Then use code like this:

$di->setShared("myCar", function () {
    return new Car();

Then car will be created only when access this servicer from di.

Hi Wojciech ,

No the car object has to be instancied inside post method. It is based on HTTP request.

What you mean ? It still will be. This way there won't be car object necessary created. Only when you access myCar from di.

edited Dec '16

The most convenient solution would be:

  1. instantiate your Car object somewhere in the local $app scope and pass it with use() statement to the finish() middleware
  2. use persistent variable to carry object within app itself

Take a look at my example (app.php):

//resolve config object into local scope
$config = $app->getSharedService('config');

$app->after(function () use ($app, $config){
// now, we have config object here inside of the middleware 
// code logic....

With persistent:

$app->persistent->auditID = 1234;

$app->error(function (\Exception $e = null) use ($app) {
    $catchable = new ErrorHandler($app->persistent->auditID); //here we have our data inside middleware event
    return $catchable->err($e);