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');
}
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');
}
相关文章推荐
- xilinx 的 HDMI输出的 IP CORE 调试
- 个人android命名(改)
- iOS画圆角矩形的方法
- [转]轻松学习Ionic (四) 修改应用图标及添加启动画面(更新官方命令行工具自动生成)
- JS红色警戒
- Xtrabackup流备份与恢复
- 使用Maven Jenkins和JMeter自动化测试
- Mysql存储过程
- python 文件、目录操作(新增、移动、删除等)
- KMP字符串查找算法
- Swift-常量与变量
- 基于S3C6410的ARM11学习(三) 核心初始化之设置中断向量表
- 得到栈的最小元素
- 算法训练 连续正整数的和
- mac分辨率设置
- 改变opacity实现图片轮播
- magent 启动时error while loading shared libraries: libevent-1.4.so.2: cannot open shared object file: N
- MSSQL和Oracle常用函数比对
- centos 安装jdk/resin/mysql
- 如何用JS判断网页中某个id的网页元素是否存在