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

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?

  • 写回答

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" );
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 VB6.0中PICTUREBOX加载本地图片无法显示
  • ¥100 关于游戏app session获取的问题
  • ¥15 MYSQL数据库建表
  • ¥15 爬虫程序爬取TTGChina网站文章代码
  • ¥35 由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作。
  • ¥15 如何用下图方法在AMESim中搭建离心泵模型
  • ¥15 C#连接服务器,请求时报Ssl/Tsl未能建立安全通道
  • ¥15 xcode15build的c++ dylib在10.15上不兼容
  • ¥15 CPLD如何实现在线逻辑分析
  • ¥15 控制面板卸载无权限!!