因为一直在开发TP所以相当然的也用了一些TP的解决办法。
一个网站总有一些 EMAIL QQ 微信 网站名一类的信息,称之为网站配置,这一些信息在网站是公用的,所以在TP开发中我们做一引父类的Controller,在其_initialize中实现配置的读取。
在symfony中,要达到此类结果,我们用服务注入进行解决,注入挺高阶的名啊,其实就是一种解决方案罢了。
在MobileBundle中新建一个Service 创建
~~~
<?php
namespace Moblie\MobleBundle\Service;
use Doctrine\ORM\EntityManager;
class ConfigServer
{
protected $configs;
protected $entityManager;
protected $cid;
public function __construct($entityManager)
{
$this->entityManager=$entityManager;
$repository = $this->entityManager->getRepository('AppBundle:Config');
$query = $repository->createQueryBuilder('p')->getQuery();
$configs = $query->getArrayResult();
$arrCon=null;
foreach ($configs as $item){
$arrCon[$item['name']]=$item['value'];
}
$this->configs=$arrCon;
}
public function getGlobals(){
return $this->configs;
}
}
~~~
$entityManager 为构造function传入的参数,类型是doctrine.orm.entity_manager,这里体现不出来,但我们在配置里加入以下代码:
~~~
app.configs:
class: Moblie\MobleBundle\Service\ConfigServer
arguments: ["@doctrine.orm.entity_manager"]
~~~
调用服务的代码我们写在一个基类里:
形式如下:
在基类的twig
~~~
{% set confs= configs.getGlobals %}
<!DOCTYPE HTML>
<html>
<head>
<title>{% block title %}{{ confs.webname }}{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<link href="{{ asset('css/bootstrap.min.css')}}" rel='stylesheet' type='text/css' />
<link href="{{ asset('css/style.css')}}" rel='stylesheet' type='text/css' />
<link href="css/font-awesome.css" rel="stylesheet">
<script src="{{ asset('js/jquery.min.js')}}"></script>
<link href='http://fonts.useso.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'>
<script src="{{ asset('js/bootstrap.min.js')}}"></script>
</head>
<body>
<div id="wrapper">
{{ include('public/top.html.twig') }}
<div id="page-wrapper">
<div class="graphs">
{% block body %}{% endblock %}
{{ include('public/footer.html.twig') }}
</div>
</div>
</div>
<link href="{{ asset('css/custom.css')}}" rel="stylesheet">
<script src="{{ asset('js/metisMenu.min.js')}}"></script>
<script src="{{ asset('js/custom.js')}}"></script>
{% block javascripts %}{% endblock %}
</body>
</html>
~~~
{% set confs= configs.getGlobals %} 这里引入了服务及服务方法。让方法读出的数组线了confs.
其他页面调用:
{% extends 'base.html.twig' %}
{% block title %}{{ confs.webname }}{% endblock %}