這個教程是基於symfony5進行編寫,以後再出高版本的symfony,那麼就可以只出一套針對這個高版本的特性進行編寫,該系列教程會一直延續更新。
點贊再看,養成習慣,微信搜索公衆號【程序員老班長】關注這個互聯網老班長,查看更多系列文章
目錄
3,使用ContainerBagInterface訪問配置變量
配置文件是symfony程序裏面的定義各種環境變量的地方。
1,目錄結構:
1 2 3 4 5 6 7 |
your-project/ ├─ config/ │ ├─ packages/ │ ├─ bundles.php │ ├─ routes.yaml │ └─ services.yaml ├─ ... |
routes.yaml
該文件爲路由配置文件
services.yaml
該文件是爲容器配置服務的文件
bundles.php
該文件是管理容器是否啓用第三方包的文件
config/packages
該目錄是安裝的第三方包的時候,所默認安裝的配置文件
2,在控制器中獲取配置變量
寫的控制器類推薦繼承於AbstractController,
這樣便可使用getParameter方法獲取變量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// src/Controller/UserController.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class UserController extends AbstractController { // ... public function index() { $projectDir = $this->getParameter('kernel.project_dir'); $adminEmail = $this->getParameter('app.admin_email'); // ... } } |
3,使用ContainerBagInterface訪問配置變量
在服務中聲明這個ContainerBagInterface類型,就可以被容器自動創建實例,後期便可調用這個實例。
namespace App\Service; // ... use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface; class MessageGenerator { private $params; public function __construct(ContainerBagInterface $params) { $this->params = $params; } public function someMethod() { // get any container parameter from $this->params, which stores all of them $sender = $this->params->get('mailer_sender'); // ... } }
4,配置文件類型
.env:定義應用程序所需的環境變量的默認值;
.env.local:定義應用程序所需的本地環境變量的值,該文件不提交到代碼庫中,並且這個文件裏面定義的變量會覆蓋.env裏面的文件。.env.test爲測試環境下使用的配置文件。
文章持續更新,可以微信搜索公衆號「 程序員老班長 」查看更多文章。