-
Notifications
You must be signed in to change notification settings - Fork 4
Automagic Resolutions
Slytherin supports resolution of parameters in an HTTP route action without the need of instantiation of 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 dependencies 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);
}
}
However, if one of the PHP classes contains arguments that need to be specified (e.g., arguments without class type-hints, etc.), the specified PHP class must be defined in a Container
then pass it to the Application
class:
// app/index.php
use Rougin\Slytherin\Application;
use Rougin\Slytherin\Container\Container;
// ...
/**
* This will be instantiated by Slytherin but
* the $text variable will return empty.
*/
class Greet
{
protected $text;
public function __construct($text)
{
$this->text = $text;
}
public function hi($name)
{
return $this->text . ' ' . $name . '!';
}
}
class Hello
{
protected $greet;
public function __construct(Greet $greet)
{
$this->greet = $greet;
}
public function hi($name)
{
return $this->greet->hi($name);
}
}
// Initialize the container ----------------------
$container = new Container;
$container->set(Greet::class, new Greet('hello'));
// -----------------------------------------------
// Initialize the Slytherin application ---
$app = new Application($container);
// ----------------------------------------
// ...
To check if greeting a name with hello
works, open the link below from a web browser and it should return the text hello rougin!
:
http://localhost:8000/hi/rougin
Note
It is best practice to specify complex classes to the Container
class prior running the Application
class.