dongqing8765
2018-05-04 13:29
浏览 88
已采纳

Symfony4 - 从控制器访问sevices.yaml

I am starting a symfony4 project, and I learned the "parameters.yaml" is now "sevice.yaml".

I setted some variables inside like:

parameters:
    smugmug.oauth_token: 'XXX'
    smugmug.oauth_token_secret: 'XXX'

And i try to access it from my controller like:

    dump($this->container->get('smugmug.oauth_token'));

But I have an error...

How does this new way of storing global variables is working?

图片转代码服务由CSDN问答提供 功能建议

我正在启动一个symfony4项目,我学会了“parameters.yaml”现在是“sevice.yaml”。

我在里面设置了一些变量,如:

 参数:
 smugmug.oauth_token:'XXX'
 smugmug.oauth_token_secret:'  XXX'
   
 
 

我尝试从我的控制器访问它,如:

  dump($ this-&gt  ; container-> get('smugmug.oauth_token')); 
   
 
 

但是我有一个错误......

这种存储全局变量的新方法是如何工作的?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanfan8360 2018-05-04 13:45
    已采纳

    I think you have forgotten to extend the Controller class

    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    
    class ArticleController extends Controller
    {
        public function controlAction()
        {
            // ...
            dump($this->container->getParameter('smugmug.oauth_token'));
            // Or this solution
            dump($this->getParameter('smugmug.oauth_token'));
            // ...
            // return a response
        }
    }
    
    已采纳该答案
    打赏 评论
  • dongpeiwei8589 2019-01-06 19:48

    Now, as Controller is deprecated and you have to use AbstractController, you need also a dependency injection for the service parameter:

    namespace App\Controller;
    
    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class SetController extends  AbstractController  {
    
        private $params;
    
        public function __construct(ParameterBagInterface $params)
        {
            $this->params = $params;
        }
    }
    

    Then you can get your parameters like this:

    $this->params->get( "app.your_stuff" );
    
    打赏 评论

相关推荐 更多相似问题