dongtun1872 2014-06-19 20:44
浏览 52
已采纳

如何在Phalcon中创建新的注射服务

I'm trying to build a basic "JSON getter" for my Phalcon-based webapp, something like that:

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

And of course I would like to make that stuff globally available, possibly as an injectable service. What could be the best way to do that? Should I implement a Phalcon\DI\Injectable? And then, how can I include the new class and feed it to the DI?

Thanks!

  • 写回答

1条回答 默认 最新

  • duanjing9739 2014-06-19 21:00
    关注

    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();
    
    //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(…);
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测