dongtun1872 2014-06-19 12: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 13: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.

    展开全部

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

报告相同问题?

悬赏问题

  • ¥100 二维码被拦截如何处理
  • ¥15 怎么解决LogIn.vue中多出来的div
  • ¥15 优博讯dt50巴枪怎么提取镜像
  • ¥30 在CodBlock上用c++语言运行
  • ¥15 求C6748 IIC EEPROM程序固化烧写算法
  • ¥50 关于#php#的问题,请各位专家解答!
  • ¥15 python 3.8.0版本,安装官方库ibm_db遇到问题,提示找不到ibm_db模块。如何解决?
  • ¥15 TMUXHS4412如何防止静电,
  • ¥30 Metashape软件中如何将建模后的图像中的植被与庄稼点云删除
  • ¥20 机械振动学课后习题求解答
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部