Ign*_*ant 1 php dependency-injection phalcon
我正在尝试为基于Phalcon的webapp构建一个基本的"JSON getter",类似于:
function getJson($url, $assoc=false)
{
$curl = curl_init($url);
$json = curl_exec($curl);
curl_close($curl);
return json_decode($json, $assoc);
}
Run Code Online (Sandbox Code Playgroud)
当然,我想将这些东西全球化,可能作为注射服务.什么是最好的方法呢?我应该实施Phalcon\DI\Injectable吗?然后,我如何包含新课程并将其提供给DI?
谢谢!
你可以扩展,Phalcon\DI\Injectable但不必.服务可以由任何类表示.这些文档很好地解释了如何使用依赖注入,特别是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();
//Register a "db" service in the container
$di->setShared('db', function() {
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
//Register a "filter" service in the container
$di->setShared('filter', function() {
return new Filter();
});
// Your json service...
$di->setShared('jsonService', function() {
return new JsonService();
});
// Then later in the app...
DI::getDefault()->getShared('jsonService')->getJson(…);
// Or if the class where you're accessing the DI extends `Phalcon\DI\Injectable`
$this->di->getShared('jsonService')->getJson(…);
Run Code Online (Sandbox Code Playgroud)
只需注意get/ setvs. getShared/ setShared,如果一次又一次地创建多次(不共享),可能会导致问题的服务,例如,在实例化时占用大量资源.将服务设置为共享可确保仅创建一次,并在之后重复使用该实例.