Symfony服务

  1. 作者QQ:67065435 QQ群:821635552

  2. 本站内容全部为作者原创,转载请注明出处!

  3. 服务的创建

    # 创建Bundle
    php bin/console generate:bundle --env=dev
    Bundle name:TestBundle
    
    # 修改TestBundle\Resources\config\services.yml
    services:
        # 服务名
        user_login:
            # 服务文件路径
            class: TestBundle\Services\Login
            # 服务中传递服务(以Orm)为例
            arguments: ["@doctrine.orm.default_entity_manager"]
    
    # 创建TestBundle\Resources\config\config.yml
        # TestBundle\Resources\config\config.yml
        # 登录相关的配置
        key1: val1
        key2: val2
    
    # 创建服务文件TestBundle\Services\Login.php
    <?php
    
    namespace TestBundle\Services;
    
    use Symfony\Component\Yaml\Yaml;
    
    class Login
    {
        private $orm;
        private $config;
    
        /**
         * 构造函数
         */
        public function __construct($orm)
        {
            //服务中调用传递过来的服务
            $this->orm = $orm;
        }
    
        /**
         * 用户登陆
         * @param $user_name
         * @param $password
         */
        public function userLogin($user_name, $password)
        {
            ...
        }
    
        /**
         * 析构函数
         */
        public function __destruct(){
            unset($this->orm);
            unset($this->config);
        }
    }
    
  4. 服务中调用服务

    Symfony服务中传递、调用服务上文(步骤1)已经说明,不在多余描述
    
  5. Symfony控制器中调用服务

    <?php
    
    namespace TestBundle\Controller;
    
    class UserController extends Controller
    {
        ...
        public function UserLoginAction()
        {
            //调用登录服务
            $user_login = $this->get("user_login");
        }
    }
    
  6. 命令行中调用服务

    $user_login = $this->getContainer()->get("user_login");
    
  7. Symfony控制器 构造函数construct中调用服务

    在src/TestBundle/TestBundle.php添加如下代码
    
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    ...
    
    private static $containerInstance = null;
    
    public function setContainer(ContainerInterface $container = null)
    {
        parent::setContainer($container);
        self::$containerInstance = $container;
    }
    
    public static function getContainer()
    {
        return self::$containerInstance;
    }
    
    构造函数调用:
    use TestBundle\TestBundle;
    
    $rbac = TestBundle::getContainer()->get('user_login');
    
Copyright © 豆包嘿嘿~ 2012-∞ 冀ICP备17033181号 all right reserved,powered by Gitbook修订: 2020-08-19 14:05:41

results matching ""

    No results matching ""