symfony学习

2016/02/12 php

创建一个bundle

php bin/console generate:bundle --namespace=Acme/TestBundle


Bundle Directory Structure

The directory structure of a bundle is simple and flexible. By default, the bundle system follows a set of conventions that help to keep code consistent between all Symfony bundles. Take a look at AcmeDemoBundle, as it contains some of the most common elements of a bundle:

Controller/
Contains the controllers of the bundle (e.g. RandomController.php).
DependencyInjection/
Holds certain Dependency Injection Extension classes, which may import service configuration, register compiler passes or more (this directory is not necessary).
Resources/config/
Houses configuration, including routing configuration (e.g. routing.yml).
Resources/views/
Holds templates organized by controller name (e.g. Random/index.html.twig).
Resources/public/
Contains web assets (images, stylesheets, etc) and is copied or symbolically linked into the project web/ directory via the assets:install console command.
Tests/
Holds all tests for the bundle.
A bundle can be as small or large as the feature it implements. It contains only the files you need and nothing else.

As you move through the guides, you'll learn how to persist objects to a database, create and validate forms, create translations for your application, write tests and much more. Each of these has their own place and role within the bundle.

composer.json配置

"autoload": {
    "psr-4": {
        "AppBundle\\": "src/AppBundle",
        "Acme\\": "src/Acme"
    },
    "classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},

composer dump-autoload 
composer install

Console Commands

创建command

bin/console generate:command AcmeBlogBundle app:add-user

[root@974d10bfd53c blog]# bin/console generate:command AcmeBlogBundle app:add-user
  created ./src/Acme/BlogBundle/Command/
  created ./src/Acme/BlogBundle/Command/AppAddUserCommand.php
Generated the app:add-user command in AcmeBlogBundle

                                         
  Everything is OK! Now get to work :).  
                                         

执行命令

bin/console app:add-user

修改command功能

./src/Acme/BlogBundle/Command/AppAddUserCommand.php:execute()方法

refer:http://symfony.com/doc/current/console.html

Database & Doctrine操作

基于第三方类库Doctrine.以下是简单的配置

# app/config/parameters.yml
parameters:
    database_host:     localhost
    database_name:     symfony
    database_user:     root
    database_password: 123456

# ...

# app/config/config.yml
doctrine:
    dbal:
        driver:   pdo_mysql
        host:     '%database_host%'
        dbname:   '%database_name%'
        user:     '%database_user%'
        password: '%database_password%'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

mysql服务器my.cnf配置

[mysqld]
# Version 5.5.3 introduced "utf8mb4", which is recommended
collation-server     = utf8mb4_unicode_ci # Replaces utf8_unicode_ci
character-set-server = utf8mb4            # Replaces utf8

我们建议不要使用MySQL的utf8字符集,因为它不支持4字节的unicode字符,并且包含它们的字符串将被截断。 这由更新的utf8mb4字符集固定。

以上配置好之后,可以通过命令行,创建数据库(需要帐号有相应的创建库权限)

[root@974d10bfd53c blog]# bin/console doctrine:database:create
Created database `symfony` for connection named default

删除数据库 
php bin/console doctrine:database:drop --force

创建实体Entity类 Entity类是一个的业务实体类,用来表示业务相关的数据信息

// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;

class Product
{
    private $name;
    private $price;
    private $description;
}

命令行创建实体

php bin/console doctrine:generate:entity

以下格式输入
AcmeBlogBundle:Blog/Post

实体与数据库的映射

Doctrine允许从实体对象中映射到数据库的操作 做好Mapping之后,用以下命令进行校验

 php bin/console doctrine:schema:validate

需要手动创建 Getters and Setters方法,以获取相应的私有数据

生成数据库表结构信息

在进行实体与DB的关系映射之后,可通过以下命令,创建相应的表结构信息

php bin/console doctrine:schema:update --force

Updating database schema...
Database schema updated successfully! "1" query was executed

存储对象到数据库中

现在您已经将Product实体映射到其相应的产品表,您可以将Product对象保存到数据库。 在控制器内部,这很容易。 将以下方法添加到捆绑包的DefaultController中:

// src/AppBundle/Controller/DefaultController.php

// ...
use AppBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;

public function createAction()
{
    // you can fetch the EntityManager via $this->getDoctrine()
    // or you can add an argument to your action: createAction(EntityManagerInterface $em)
    $em = $this->getDoctrine()->getManager();

    $product = new Product();
    $product->setName('Keyboard');
    $product->setPrice(19.99);
    $product->setDescription('Ergonomic and stylish!');

    // tells Doctrine you want to (eventually) save the Product (no queries yet)
    $em->persist($product);

    // actually executes the queries (i.e. the INSERT query)
    $em->flush();

    return new Response('Saved new product with id '.$product->getId());
}

// if you have multiple entity managers, use the registry to fetch them
public function editAction()
{
    $doctrine = $this->getDoctrine();
    $em = $doctrine->getManager();
    $em2 = $doctrine->getManager('other_connection');
}

从数据库中取数据对象Fetching Objects from the Database

public function showAction($productId)
{
    $product = $this->getDoctrine()
        ->getRepository(Product::class)
        ->find($productId);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$productId
        );
    }

    // ... do something, like pass the $product object into a template
}

布署

检查环境依赖
php bin/symfony_requirements

通常这个配置文件不要提交到版本库,是一些动态配置 
app/config/parameters.yml

第三方库更新
composer install --no-dev --optimize-autoloader
composer dump-autoload --optimize --no-dev --classmap-authoritative

清除缓存
 php bin/console cache:clear --env=prod --no-debug --no-warmup
 php bin/console cache:warmup --env=prod

导出资源
 php bin/console assetic:dump --env=prod --no-debug

ref:http://symfony.com/doc/current/doctrine.html

安装调试器

composer require profiler

注解功能 SensioFrameworkExtraBundle

composer require annotations

Search

    Table of Contents