symfony学习笔记3.4(bundle、service、doctrine的使用…)

yii、laravel框架都是基于symfony组件衍生,symfony的强大不用多说。文档里有的,很好找的就不写了

附:

  1. symfony官网  https://symfony.com/doc/3.4 
  2. yml语法(秒懂的那种)https://www.jianshu.com/p/a8252bf2a63d
  3. 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=Acme/TestBundle

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>注册服务

  1. 在需要的Bundle下新建服务文件夹(service)
  2. 在新建的文件夹(service)下,建立文件(名字根据业务逻辑来)

2>调用服务


//!!!以下方式必须先use,即:
use namespace\yourServerClass; 

//方式1、在controller中 $this->container->get('服务的id')
$doctrine = $this->container->get('doctrine');

//方式2、在controller中 $yourVariate= $this->get(服务的类名::class);
$yourVariate= $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

注意:每次更新完实体后要运行上面的update命令,否则对实体的更改不能及时生效到数据库!

2>连接多数据库:

https://www.cnblogs.com/dluf/archive/2013/01/17/2864269.html

3>一些概念:

// 多对一:当前表多条记录和目标表的一条记录对应;

//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;

// 一对多:

//Disasters.php

/**
 * @ORM\OneToMany(targetEntity="Chatmessages", mappedBy="disasterid", cascade={"persist", "remove"})
 * 
 */
protected $chatmessages;

```

4>操作数据库:

1、常用操作方式

  • Repository
  • dql 
  • queryBuilder

// eg
# 使用Repository
$this->em->getRepository('App\Entity\ResourceType')->findBy();
$this->em->getRepository(ResourceType::class)->findBy();

# 使用createQuery创建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())
));
$res = $query->getResult();

4、文件系统

1>事件对象提供以下方法。

  • getFile:获取上传的文件。Gaufrette\FileSymfony\Component\HttpFoundation\File\File的实例.
  • getRequest获取当前请求,包括自定义变量。
  • getResponse:获取响应对象以添加自定义返回数据。
  • getType*获取当前上载的映射名称。如果有多个映射和EventListener,则非常有用。
  • getConfig:获取映射的配置。

5、http

1>symfony获取请求的所有参数

 适用于GET POST PUT DELETE等所有常用方式,

public function getParams($request){
	$query = $request->query->all();      # get
	$request = $request->request->all();  # post和其他
	return array_merge($query,$params);
}

// 接收文件
$files = $request->files->all();          # 文件

参考自:Symfony\Component\HttpFoundation\Request.php

2>symfony返回一个http状态码

return new Response('parameter error',400);

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('参数名');
    }
}

如parameters.yml里的

--------------------------

未完待续……

最后更新于:2020-4-11

猜你喜欢

转载自blog.csdn.net/qq_36110571/article/details/87855221
今日推荐