1. 程式人生 > >symfony2中對於注入的進一步理解

symfony2中對於注入的進一步理解

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');

        }