You could extend Phalcon\DI\Injectable
but don't have to. A service can be represented by any class. The docs pretty well explain how to work with the dependency injection in general and specifically with Phalcon.
class JsonService
{
public function getJson($url, $assoc=false)
{
$curl = curl_init($url);
$json = curl_exec($curl);
curl_close($curl);
return json_decode($json, $assoc);
}
}
$di = new Phalcon\DI();
$di->setShared('db', function() {
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
$di->setShared('filter', function() {
return new Filter();
});
$di->setShared('jsonService', function() {
return new JsonService();
});
DI::getDefault()->getShared('jsonService')->getJson(…);
$this->di->getShared('jsonService')->getJson(…);
Just pay attention to get
/ set
vs. getShared
/ setShared
, there are services that may cause problems if created multiple times over and over again (not shared), e.g., take a lot of resources when instantiated. Setting service as shared ensures it's created only once and the instance is reused there after.