-
Notifications
You must be signed in to change notification settings - Fork 4
Automagic Resolutions
Rougin Gutib edited this page Aug 9, 2024
·
16 revisions
Slytherin supports resolution of parameters in an HTTP route action without the need of instantiation one of its specified parameters (e.g., new Hello
). To automagically create class instances, kindly specify the name of the class to its respective argument:
// app/index.php
// ...
class Hello
{
public function greet($name)
{
return 'Hello ' . $name . '!';
}
}
/**
* The $hello argument will be instantiated with the
* Hello class, without need to code "new Hello" to it.
*/
$app->get('/hi/{name}', function ($name, Hello $hello)
{
return $hello->greet($name);
});
// ...
Then try to open the link below from a web browser and it should return the text Hello royce!
:
http://localhost:8000/hi/royce
Resolving resolutions only works automagically on PHP classes with simple dependencies like the sample code below:
class Greet
{
public function hi($name)
{
return 'Hi ' . $name . '!';
}
}
/**
* This is a simple class as it can be
* defined manually simply below:
*
* $hello = new Hello(new Greet);
*/
class Hello
{
protected $greet;
public function __construct(Greet $greet)
{
$this->greet = $greet;
}
public function hi($name)
{
return $this->greet->hi($name);
}
}