router icon indicating copy to clipboard operation
router copied to clipboard

Integration with other libraries when using Class@Method calls

Open xergio opened this issue 9 years ago • 8 comments

Hi, as the title says, how can I use external variables inside the method's class? The only 2 solutions I can imagine are:

  • to use global $tpl; call inside the method.
  • to use: $router->get('/', function() use ($tpl) { $c = new \App\Controllers\User($tpl); $c->showProfile(); });

There are any other option?

xergio avatar May 30 '17 10:05 xergio

Your second example the closure is the best option. But instead of using an anonymous function you could use an existing function aka callback function. Global is not what you want to use.

JBlond avatar May 30 '17 12:05 JBlond

What you're aiming, it's exactly what Laravel does.

I will think on a solution and provide a Pull Request for it.

@bramus what you think about it?

ovflowd avatar May 30 '17 14:05 ovflowd

mmm... @JBlond how do you suggest me to use an existing function?

When I need to pass, for example, the controller, the method, $tpl and $id (if the route is something like /test/(\d+) ), I can't see anything but an anonymous function...

xergio avatar May 30 '17 14:05 xergio

@xergio Somethings like this.

function myCallBackFunction(){
    //do fanzy things
}
$router->get('/', myCallBackFunction());

See http://php.net/manual/de/language.types.callable.php

JBlond avatar May 31 '17 09:05 JBlond

In terms of code readability and simplicity I won't recommend @JBlond's method.

In case of using Class@Method, you are strictly following the MVC pattern. In the same case, Class@Method would be a callable. "a callable".

Need advice to @JBlond that actually Callable's are a type of entities on php. In the case of myCallbackFunction() and Method@Class, they aren't really callables.

What the Router does it's check the existence of the callability of them, and if they really exists.

Actually on the Class@Method, you need provide a full namespace.

I may do a commit creating the ability of adding namespaces on the environment, and also passing variables to the methods like on Laravel.

Example.:

$router->get('/my/route/with/{some}/{data}', 'MyClass@Method');

And something like that for namespace:

$router->add('/App/Controllers');

ovflowd avatar May 31 '17 12:05 ovflowd

@sant0ro I commented https://github.com/bramus/router/issues/37#issuecomment-304859575 at using closure is the best option. Well using native call_user_func would work.

JBlond avatar May 31 '17 13:05 JBlond

Yes using Callables would be the best option.

ovflowd avatar May 31 '17 14:05 ovflowd

With #38 being merged and closed this feature is now on master. Feel free to test. If found OK I'll tag this release as 1.2 :-)

bramus avatar Oct 06 '17 21:10 bramus