【问题标题】:How to create a new injectable service in Phalcon如何在 Phalcon 中创建新的可注入服务
【发布时间】:2014-06-19 20:44:22
【问题描述】:

我正在尝试为基于 Phalcon 的 web 应用程序构建一个基本的“JSON getter”,类似于:

function getJson($url, $assoc=false)
{
$curl = curl_init($url);
$json = curl_exec($curl);
curl_close($curl);
return json_decode($json, $assoc);
}

当然,我想让这些东西在全球范围内可用,可能作为一种可注入的服务。最好的方法是什么?我应该实施 Phalcon\DI\Injectable 吗?然后,如何包含新类并将其提供给 DI?

谢谢!

【问题讨论】:

  • 你可能想看看特质。特质也可能是解决您问题的好方法。

标签: php dependency-injection phalcon


【解决方案1】:

您可以扩展Phalcon\DI\Injectable,但不必这样做。服务可以由任何类表示。 docs 很好地解释了如何使用依赖注入,特别是使用 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(…);

请注意get / set vs. getShared / setShared,有些服务如果反复创建(不共享)可能会导致问题,例如,占用大量实例化时的资源。将服务设置为共享可确保它只创建一次,然后在此重复使用该实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多