您的位置:首页 > 其它

symfony2中对于注入的进一步理解

2016-02-22 14:35 267 查看
1.首先在appBundle里面的services.yml中写服务的名字,class以及要注入的参数

app.redis_service:

class: AppBundle\Service\RedisService

arguments: ['@snc_redis.data']

举个例子

我在控制器中可能会写

$redis = $this->container->get('snc_redis.data');

这时候我就需要将snc_redis.data为参数传入其中,然后将redis作为services里面的变量,注入到__construct中

例子:

protected $redis;

function __construct($redis)

{

$this->redis = $redis;

}

/**

* 从redis获取数据

*/

public function getCacheData($key)

{

return json_decode($this->redis->get($key));

}

/**

* 存入数据到redis

*/

public function setCacheData($key, $values, $lifeTime = 1200)

{

$this->redis->set($key,json_encode($values));

$this->redis->expire($key,$lifeTime);

}

这样services就写好了。

3.再控制的使用

$cacheService = $this->get('app.redis_service');

$paymentList = $cacheService->getCacheData('sy_payment');

if (!isset($paymentList)) {

$paymentData = $paymentService->getList();

$paymentHashData = array();

foreach ($paymentData as $payment) {

$paymentHashData[$payment['id']] = $payment;

}

$cacheService->setCacheData('sy_payment', $paymentHashData);

$paymentList = $cacheService->getCacheData('sy_payment');

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: