klein / klein.php

A fast & flexible router
MIT License
2.67k stars 289 forks source link

is it possible to create methods with parameters in $app->register #397

Open karamusluk opened 6 years ago

karamusluk commented 6 years ago

As title indicates, i am wondering whther it is possible to create a method like

`$app->register('abc', function($a, $b) {

   return $a."<br>".$b;

});`

and then use it like echo $app->abc("hello", "xxx");

Thanks.

nbish11 commented 6 years ago

No, but it is really easy to do yourself.

// "MyProject/MyApp.php"

namespace MyProject;

use Klein\Exceptions\DuplicateServiceException;

class MyApp extends \Klein\App
{
    public function factory($name, $closure)
    {
        if (isset($this->services[$name])) {
            throw new DuplicateServiceException('A service is already registered under '. $name);
        }

        $this->services[$name] = $closure;
    }
}

Now use the instance of your class instead:

$myApp = new MyProject\MyApp();
$klein = new Klein\Klein(null, $myApp);

$app = $klein->app();
$app->factory('abc', function ($a, $b) {
    return $a . '<br>' . $b;
});

echo $app->abc('hello', 'xxx');