天天看點

symfony學習筆記3.4(bundle、service、doctrine的使用…)6、擷取配置的參數值

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=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>注冊服務

  1. 在需要的Bundle下建立服務檔案夾(service)
  2. 在建立的檔案夾(service)下,建立class(名字根據業務邏輯來,symfony會自動注冊/src下的類)
  3. 也可以在/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>連接配接多資料庫:

Symfony2 多資料庫連接配接 - d&lufd - 部落格園

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、常用操作方式

  1. Repository  
  2. dql 
  3. queryBuilder 
  4. 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