例子里用一个很是简单的写日志的服务来演示php
第一步 建立服务 LogServicehtml
在当前bundle目录下建立Service目录 而后建立LogService.php文件 我这里是src/Milk/CoffeeBundle/Service/LogService.php
数组
<?php /** * Created by PhpStorm. * User: mot * Date: 14-2-6 * Time: 上午6:50 */ namespace Milk\CoffeeBundle\Service; class LogService { protected $log; protected $config; protected $file; protected $line; public function __construct( $config) { $this->config = $config; } public function exception_path($file, $line) { $this->file = $file; $this->line = $line; return $this; } public function writeLog( $log) { if( FALSE == file_exists( $this->config['log_path'])) { file_put_contents( $this->config['log_path'] , ''); } $this->log = "[".date('Y-m-d h:i:s')."] - ".$this->file.":line ".$this->line." Exception : " .$log. "\r\n"; return $this; } public function flush() { file_put_contents( $this->config['log_path'] , $this->log , FILE_APPEND ); return $this; } public function readLog() { $log = file_get_contents( $this->config['log_path']); if( ! $log) return FALSE; $log = explode("\r\n" , $log); $log = implode('<br/>' , $log); return $log; } }
这是我定义的一个小log类 功能比较简单 exception_path记录日志发生位置 writeLog修改日志内容 flush把日志写入文件 readLog读取日志文件this
第二步 添加定义跟参数 在当前bundle下面的Resources/config/services.yml
spa
个人services.yml位置是 src/Milk/CoffeeBundle/Resources/config/service.yml日志
parameters: milk_coffee.log.class: Milk\CoffeeBundle\Service\LogService milk_coffee.log.config: log_path: c:/file_system.log services: milk_coffee.log: class: %milk_coffee.log.class% arguments: [%milk_coffee.log.config%]
这里解释一下 code
parameters: milk_coffee.log.class: Milk\CoffeeBundle\Service\LogService milk_coffee.log.config: log_path: c:/file_system.log
这是咱们要用的参数 例如咱们要写log 须要提供log文件的位置 这里提供了文件的位置orm
c:/file_system.log
在yml解析以后
xml
milk_coffee.log.config: log_path: c:/file_system.log
这个格式就是一个php数组 array( 'log_path' => 'c:/file_system.log' );htm
这里是咱们定义服务class的位置
services: milk_coffee.log: class: %milk_coffee.log.class% arguments: [%milk_coffee.log.config%]
"%"中的变量是咱们上面定义的参数%
%milk_coffee.log.class% 即对应 "Milk\CoffeeBundle\Service\LogService"
%milk_coffee.log.config% 即对应 "log_path: c:/file_system.log"
这样服务就定义好了
第三步 在咱们的逻辑代码中使用服务
<?php namespace Milk\CoffeeBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class DefaultController extends Controller { public function indexAction($name) { // if( FALSE === $this->get('milk_coffee.log')->readLog()) $this->get('milk_coffee.log') ->exception_path(__FILE__,__LINE__) ->writeLog('First log') ->flush(); return new Response( $this->get('milk_coffee.log')->readLog() , 200); //return $this->render('MilkCoffeeBundle:Default:index.html.twig', array('name' => $name)); } }
这里用 $this->get('milk_coffee.log') 就得到了咱们LogService的实例 省去了 new LogService( array() ) 这种过程 并且在当前bundle的逻辑代码中随处可用
milk_coffee.log是咱们定义在Resources/config/service.yml中的服务名
访问这个控制器的路由地址 就能够看到效果了