yii、laravel框架都是基于symfony组件衍生,symfony的强大不用多说。文档里有的,很好找的就不写了
附:
- symfony官网 https://symfony.com/doc/3.4
- yml语法(秒懂的那种)https://www.jianshu.com/p/a8252bf2a63d
- twig语法 https://www.kancloud.cn/yunye/twig-cn/159454
--------------------------
学习笔记(v 3.4.22 附symfony5.0笔记) :
# 展示所有命令
php bin/console
1、bundle
1>创建
php bin/console generate:bundle --namespace=BundleNamespace\YourBundle
2>注册
// app/AppKernel.php
public function registerBundles()
{
$bundles = [
//…,
new BundleNamespace\YourBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'])) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
2、服务
一旦你启动一个Symfony应用程序,你的容器已经包含许多服务。这些就像工具*等待你利用它们。
可以通过如下命令查看全部服务:
php bin/console debug:container
1>注册服务
- 在需要的Bundle下新建服务文件夹(service)
- 在新建的文件夹(service)下,建立class(名字根据业务逻辑来,symfony会自动注册/src下的类)
- 也可以在/config/service.yml手动注册
# /config/service.yml
services:
# ...
# this is the service's id
App\Service\SiteUpdateManager:
public: true
附.官网文档 》
2>调用服务
//方式1、在controller中 $this->container->get('服务的id')
$doctrine = $this->container->get('doctrine');
//方式2、在controller中 $service = $this->get(服务的类名::class);
//!!!此方式必须先use,即:use youerNamespace\yourServiceClass;
$service = $this->get(yourServiceClass::class);
//方式3、从服务容器获取服务
$doctrine = $this->getContainer()->get('doctrine');
//方式4、依赖注入方式获取服务
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RunActionListenter
{
protected $em;
protected $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage,ContainerInterface $container){
$this->tokenStorage = $tokenStorage;
$this->em = $container->get('doctrine')->getManager();
}
}
3、数据库
1>常用命令:
#)、通过数据库生成实体类
php bin/console doctrine:mapping:import --force AppBundle annotation
//AppBundle:bundle名
//annotation:实体类格式 xml,yml, annotation
#)、通过交互式的问题生成实体类
php bin/console doctrine:generate:entity
#)、验证映射:
php bin/console doctrine:schema:validate
#)、生成geter、seter
php bin/console doctrine:generate:entities AppBundle/Entity --no-backup
#)、根据实体类更新数据库
php bin/console doctrine:schema:update --force
注意:每次更新完实体(entity)后要运行上面的update命令,否则对实体的更改不能同步到数据库,查询时会报错!
2>连接多数据库:
3>一些概念:
// 一对多:当前表(entity)的一条记录和目标表(targetEntity值指向的那个表)的多条记录对应;
//Disasters.php
/**
* @ORM\OneToMany(targetEntity="Chatmessages", mappedBy="disasterid", cascade={"persist", "remove"})
*
*/
protected $chatmessages;
// 多对一:当前表(entity)多条记录和目标表(targetEntity值指向的那个表)的一条记录对应;
//Chatmessages.php
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Role", inversedBy="users")
* @ORM\JoinColumn(name="roles", referencedColumnName="id")
* :
* targetEntity 目标实体类
* inversedBy/mappedBy 要映射到的目标类里的那个属性
* (inversedBy一般和Joincolumns并存,处于name外键所在的类;mappedBy为要映射到的类)
* name 当前表中外键的名字
* referencedColumnName 参考属性
*/
private $roles;
其他的一对一,多对多概念和上面类似,相信不用再多写废话了···
4>操作数据库:
1、常用操作方式
- Repository
- dql
-
queryBuilder
-
executeQuery 执行原生sql
# 使用Repository查询
// find($id) 通过id查询记录
// findBy(array('id' => $id)) 查询满足条件的条记录
// findOneBy(array('id' => $id)) 查询满足条件的一条记录
!!!注意,条件数组里的key(比如这里的id)不是数据库里的表字段,必须是entity里存在的属性。
// eg
$this->em->getRepository('App\Entity\ResourceType')->find($id);
$this->em->getRepository(ResourceType::class)->find($id);
$this->em->getRepository(ResourceType::class)->findBy(array('id' => $id));
# 使用DQL查询
$query = $em->createQuery('SELECT s FROM AppBundle\Entity\Signin s
WHERE s.userid = :uId
AND s.signintime BETWEEN :date AND :endDate');
$query->setParameters(array(
'uId' => $u->getId(),
'date' => date('Y',time()).'-01-01',
'endDate' => date('Y-m-d',time())
));
#$query->setMaxResults(10); 取10条记录
$res = $query->getResult();
# 使用executeQuery
$query = $this->em->getConnection()->prepare("SELECT * FROM project WHERE `open`=1 ORDER BY RAND() LIMIT 1");
$res = $query->executeQuery()->fetchAllAssociative();
4、文件系统
1>获取上传的文件
- $request->files->all();获取上传的文件。
2>文件操作
- Symfony\Component\Filesystem\Filesystem; new这个类即可使用syfmony文件系统。
5、http
1>从Request获取请求的所有数据
适用于GET POST PUT DELETE等所有常用方式,
public function getParams($request){
$query = $request->query->all(); # get
$request = $request->request->all(); # post和其他
$data = json_decode($request->getContent(), true); # json
return array_merge($query,$params);
}
// 接收文件
$files = $request->files->all(); # 文件
参考自:Symfony\Component\HttpFoundation\Request.php
2>http响应/Response
# 返回一个http状态码
return new Response('parameter error', 400);
# 返回json
$this->json([]);
$this->json($entiyObj);
# 返回file
return $this->file(new File('path/to/file'));
6、获取配置的参数值
# 在控制器里 可以直接调用getParameter获取参数
$this->getParameter('参数名');
# 在其他服务里
use Symfony\Component\DependencyInjection\ContainerInterface;
class SceneSplit
{
protected $container;
// 先注入服务容器
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function split($file)
{
// 调用getParameter获取参数
$url = $this->container->getParameter('参数名');
}
}
--------------------------
未完待续……
最后更新于:2022-3-22