php_Symfony_项目实战全过程记录

为了大家方便交流加Symfony技术交流群, 182983780

 

微信公众号:

 

今天是2017年1月8号,正式接收到一个Symfony 的项目,准备全程记录遇到的问题及解决方法,之前被通知学习该框架,只是一直没有机会做项目,今天终于可以做了,希望2017把Symfony学的能会使用,能够解决基本问题,能够独立新建项目。。。。。2017开始了。。。。。。。。

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

1月8号,更新代码,由于有两三个月没有看symfony了,上来就遇到了之前的问题,幸好遇到过(以下XXX代表项目名称)哈哈

1:更新代码。。。。。

2:跑项目

问题如下:

$ php bin/console server:run
PHP Warning:  require(D:\home\workspace\XXX\app/../vendor/autoload.php): f
ailed to open stream: No such file or directory in D:\home\workspace\XXX\a
pp\autoload.php on line 7
PHP Fatal error:  require(): Failed opening required 'D:\home\workspace\XXX
\app/../vendor/autoload.php' (include_path='.;D:\php-5.5.30-nts-Win32-VC11-x64\
pear') in D:\home\workspace\XXX\app\autoload.php on line 7

解释:没有安装依赖包

 

问题解决:执行$ php cocomposer.json  composer.lock  composer.phar

 

运行后如下:

 

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 33 installs, 0 updates, 0 removals
  - Installing doctrine/lexer (v1.0.1) Loading from cache
  - Installing doctrine/annotations (v1.2.7) Loading from cache
  - Installing twig/twig (v1.28.2) Downloading: 100%
  - Installing symfony/polyfill-util (v1.3.0) Downloading: 100%
  - Installing paragonie/random_compat (v2.0.4) Downloading: 100%
  - Installing symfony/polyfill-php70 (v1.3.0) Downloading: 100%
  - Installing symfony/polyfill-php56 (v1.3.0) Downloading: 100%
  - Installing symfony/polyfill-mbstring (v1.3.0) Downloading: 100%
  - Installing symfony/symfony (v3.2.1) Downloading: 100%
  - Installing symfony/polyfill-intl-icu (v1.3.0) Downloading: 100%
  - Installing psr/log (1.0.2) Loading from cache
  - Installing psr/cache (1.0.1) Loading from cache
  - Installing doctrine/inflector (v1.1.0) Loading from cache
  - Installing doctrine/collections (v1.3.0) Loading from cache
  - Installing doctrine/cache (v1.6.1) Loading from cache
  - Installing doctrine/common (v2.6.2) Downloading: 100%
  - Installing jdorn/sql-formatter (v1.2.17) Loading from cache
  - Installing doctrine/doctrine-cache-bundle (1.3.0) Loading from cache
  - Installing doctrine/dbal (v2.5.5) Loading from cache
  - Installing doctrine/doctrine-bundle (1.6.4) Loading from cache
  - Installing doctrine/instantiator (1.0.5) Loading from cache
  - Installing doctrine/orm (v2.5.5) Loading from cache
  - Installing incenteev/composer-parameter-handler (v2.1.2) Loading from cache
  - Installing sensiolabs/security-checker (v4.0.0) Loading from cache
  - Installing sensio/distribution-bundle (v5.0.15) Downloading: 100%
  - Installing sensio/framework-extra-bundle (v3.0.16) Loading from cache
  - Installing monolog/monolog (1.22.0) Downloading: 100%
  - Installing symfony/monolog-bundle (3.0.1) Downloading: 100%
  - Installing symfony/polyfill-apcu (v1.3.0) Downloading: 100%
  - Installing swiftmailer/swiftmailer (v5.4.4) Downloading: 100%
  - Installing symfony/swiftmailer-bundle (v2.4.0) Downloading: 100%
  - Installing sensio/generator-bundle (v3.1.2) Downloading: 100%
  - Installing symfony/phpunit-bridge (v3.2.1) Downloading: 100%
paragonie/random_compat suggests installing ext-libsodium (Provides a modern cry
pto API that can be used to generate random bytes.)
doctrine/doctrine-cache-bundle suggests installing symfony/security-acl (For usi
ng this bundle to cache ACLs)
sensio/framework-extra-bundle suggests installing symfony/psr-http-message-bridg
e (To use the PSR-7 converters)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages
to AWS services like DynamoDB)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages
 to a CouchDB server)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an A
MQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a M
ongoDB server)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log message
s to a GrayLog2 server)
monolog/monolog suggests installing mongodb/mongodb (Allow sending log messages
to a MongoDB server via PHP Driver)
monolog/monolog suggests installing php-amqplib/php-amqplib (Allow sending log m
essages to an AMQP server using php-amqplib)
monolog/monolog suggests installing php-console/php-console (Allow sending log m
essages to Google Chrome)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages
to Rollbar)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages
to an Elastic Search server)
monolog/monolog suggests installing sentry/sentry (Allow sending log messages to
 a Sentry server)
Generating autoload files
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Creating the "app/config/parameters.yml" file
Some parameters are missing. Please provide them.
database_host (127.0.0.1):
database_port (null):
database_name (symfony):
database_user (root):
database_password (null):
mailer_transport (smtp):
mailer_host (127.0.0.1):
mailer_user (null):
mailer_password (null):
secret (ThisTokenIsNotSoSecretChangeIt):
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

 // Clearing the cache for the dev environment with debug
 // true

 [OK] Cache for the "dev" environment (debug=true) was successfully cleared.

> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::installAssets

 Trying to install assets as relative symbolic links.

 --------- ------------- ----------------
            Bundle        Method / Error
 --------- ------------- ----------------
  WARNING   XinXiBundle   copy
 --------- ------------- ----------------

 ! [NOTE] Some assets were installed via copy. If you make changes to these
 !        assets you have to run this command again.

 [OK] All assets were successfully installed.

> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::installRequirementsFi
le
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::prepareDeploymentTarg
et

 运行中以下部分是要输入的:但是我都默认的回车,过一会再研究

Some parameters are missing. Please provide them.
database_host (127.0.0.1):
database_port (null):
database_name (symfony):
database_user (root):
database_password (null):
mailer_transport (smtp):
mailer_host (127.0.0.1):
mailer_user (null):
mailer_password (null):
secret (ThisTokenIsNotSoSecretChangeIt):

 上面这些代码不用管,一路回车就好;

 今天是1月9号

3:接下来创建数据库(我使用的是PostgreSQL,当然Mysql也行)

(官方数据库配置教程英文http://symfony.com/doc/master/doctrine.html;中文http://www.symfonychina.com/doc/current/doctrine.html)

   1〉找到项目目录中的/app/config.yml

       找到doctrine:将以下代码替换

doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8

 2〉找到项目目录中的/app/config.yml

 把下面代码替换进去

parameters:
    database_driver: pdo_pgsql --驱动,如果没有需要下载,我记得还需要更改一个php的配置文件,
    database_host: localhost
    database_port: 5432
    database_name: 数据库名称
    database_user: 数据库用户名 --我还不知道怎么自动创建
    database_password: 数据库用户密码--我还不知道怎么自动创建
    mailer_transport: smtp
    mailer_host: localhost
    mailer_user: 111@wqwqww.com(随便)
    mailer_password: llkjjkljlk(随便)
    secret: ThisTokenIsNotSoSecretChangeIt

 3〉好了你只需要执行一句命令就可以了如下

$ php bin/console doctrine:database:create
--显示成功
Created database "XXXX" for connection named default

 创建数据库(以上之创建了一个数据库,后来发现不怎么对)2:

(项目开发中往往会创建三个数据库dev,prod,test;我的这个项目中有个数据库创建脚本db.sql,执行psql -Upsotgres<db.sql就可以创建了,当然这只是PostgresSQL 的命令)

1>脚本如下:

create user XXX with password 'XXX' ;
ALTER USER XXX WITH PASSWORD 'XXX';

create database XXX_dev with encoding='utf8' ;
create database XXX_prod with encoding='utf8' ;
create database XXX_test with encoding='utf8' ;

grant all privileges on database XXX_dev to XXX ;
grant all privileges on database XXX_test to XXX;
grant all privileges on database XXX_prod to XXX;

\connect XXX_dev;
create schema extensions;
create extension hstore schema extensions;
ALTER DATABASE XXX_dev SET search_path to "$user",public,extensions;
alter database XXX_dev owner to XXX;
alter schema public owner to XXX;
alter schema extensions owner to XXX;
GRANT USAGE ON SCHEMA public to XXX;

\connect XXX_prod;
create schema extensions;
create extension hstore schema extensions;
ALTER DATABASE XXX_dev SET search_path to "$user",public,extensions;
alter database XXX_dev owner to XXX;
alter schema public owner to XXX;
alter schema extensions owner to XXX;
GRANT USAGE ON SCHEMA public to XXX;


\connect XXX_test;
create schema extensions;
create extension hstore schema extensions;
ALTER DATABASE XXX_dev SET search_path to "$user",public,extensions;
alter database XXX_dev owner to XXX;
alter schema public owner to XXX;
alter schema extensions owner to XXX;
GRANT USAGE ON SCHEMA public to XXX;

 

 2>好了,按照开发,生产,测试的方式创建吧;数据库脚本执行完后,你就发现你的Postgresql数据库了增加了三个数据库分别是XXX_dev,XXX_prod,XXX_test那么有三个文件需要配置分别是

3>config_dev,config_prod,config_test这三个文件分别配置数据库信息,分别都添加上:

 

doctrine:
    dbal:
        driver:   pdo_pgsql
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name_dev%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8

 

  4〉千万别忘了配置parameters.yml.dist,要不然引入第三方Bundle时会找不到database_name

  代码如下:

     

# This file is a "template" of what your parameters.yml file should look like
# Set parameters here that may be different on each deployment target of the app, e.g. development, staging, production.
# http://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
parameters:
    database_host:     127.0.0.1
    database_port:     ~
    database_name_dev:     xinxi_dev
    database_name_test:     xinxi_test
    database_name_prod:     xinxi_prod
    database_user:     xinxi
    database_password: xinxi
    # You should uncomment this if you want use pdo_sqlite
    # database_path: "%kernel.root_dir%/data.db3"

    mailer_transport:  smtp
    mailer_host:       localhost
    mailer_user:       111@wqwqww.com
    mailer_password:   llkjjkljlk

    # A secret key that's used to generate certain security-related tokens
    secret:            ThisTokenIsNotSoSecretChangeIt

 

 

 

4 。到现在为止运行项目还是正常启动,好了,现在开始创建Bundle(什么是Bundle自行官网我现在也不懂,现学现查吧),我的项目目录结构为src/项目名/Bundle名;

     创建bundle的命令(我习惯命令执行,当然可以手工创建,例如别人家的博客写得http://blog.csdn.net/mieshihanyu/article/details/47104917)

  

$ php bin/console generate:bundle --namespace=项目名/Bundle名

 我的目录结构如图'

 

  运行如下:其中需要提示几点(交互内容在代码中标注,可参照http://oskarcalvo.com/php-appconsole-generatebundle-en-la-versi%C3%B3n-28-de-symfony)

$ php bin/console generate:bundle --namespace=XXX/CompanyBundle


  Welcome to the Symfony bundle generator!


Are you planning on sharing this bundle across multiple applications? [no]: (直接回车就可以,这里还不知道具体干什么的)

Your application code must be written in bundles. This command helps
you generate them easily.

Give your bundle a descriptive name, like BlogBundle.
Bundle name [XXX/CompanyBundle]:(直接回车就可以,如果自己写名称的话需要注意Bundle在名称的后面且B要大写,这应该是约定吧)

In your code, a bundle is often referenced by its name. It can be the
concatenation of all namespace parts but it's really up to you to come
up with a unique name (a good practice is to start with the vendor name).
Based on the namespace, we suggest XinCompanyBundle.

Bundle name [XXXCompanyBundle]:(直接回车就可以,默认创建一个XXXCompanyBundle,如果你要自己名命也会直接在src目录下生成Bundle,不会在XXX项目下生成Bundle)

Bundles are usually generated into the src/ directory. Unless you're doing something custom, hit enter to keep this default!

Target Directory [src/]:(直接回车就可以)

What format do you want to use for your generated configuration?

Configuration format (annotation, yml, xml, php) [annotation]:(直接回车就可以,默认就是annotation了)


  Bundle generation

(以下就是生成的文件以及修改的文件)
> Generating a sample bundle skeleton into D:\home\workspace\quanxinxi\app/../sr
c/Xin/CompanyBundle
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/XinCompanyBun
dle.php
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Controller/
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Controller/De
faultController.php
  created D:\home\workspace\XXXX\app/../tests/XinCompanyBundle/Controller/
  created D:\home\workspace\XXXX\app/../tests/XinCompanyBundle/Controller/D
efaultControllerTest.php
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Resources/vie
ws/Default/
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Resources/vie
ws/Default/index.html.twig
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Resources/con
fig/
  created D:\home\workspace\XXXX\app/../src/Xin/CompanyBundle/Resources/con
fig/services.yml
> Checking that the bundle is autoloaded
> Enabling the bundle inside D:\home\workspace\XXXX\app\AppKernel.php
  updated D:\home\workspace\quanxinxi\app\AppKernel.php
> Importing the bundle's routes from the D:\home\workspace\XXXX\app\config\
routing.yml file
  updated D:\home\workspace\XXXX\app/config/routing.yml
> Importing the bundle's services.yml from the D:\home\workspace\XXXX\app\config\config.yml file
  updated D:\home\workspace\XXXX\app/config/config.yml


  Everything is OK! Now get to work :).

 到现在项目还是正常启动;

那么接下来就命令创建实体什么的了;

5。 创建实体:

依旧执行命令:

$ php bin/console doctrine:generate:entity

 

运行如下:中间会与你交互,如下注视

$ php bin/console doctrine:generate:entity


  Welcome to the Doctrine2 entity generator



This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.(--这里是告诉你创建一个这样的实体Bundle名字:实体名字,只以Bundle名字需要加上你的项目名字XXXBundle名字)

The Entity shortcut name: Company (这样写就不对了,我本以为就是名字呢)
 The entity name isn't valid ("Company" given, expecting something like AcmeBlog
Bundle:Blog/Post)
The Entity shortcut name: CompanyBundle:Company(让我重新输入,我以为这样写就对了呢,XXXBundle:要创建的实体名)
Bundle "CompanyBundle" does not exist.
The Entity shortcut name: /Xin/CompanyBundle:Company(又让我重新输入,我想上面写的不对是不是因为命名空间没写呢?于是这样写还不对)
 The entity name isn't valid ("/Xin/CompanyBundle:Company" given, expecting some
thing like AcmeBlogBundle:Blog/Post)
The Entity shortcut name: XinCompanyBundle:Company(这次终于对了,要这样写啊啊啊啊啊啊,可能是种约定吧,这样写---项目明Bundle名:实体名字)

Determine the format to use for the mapping information.

Configuration format (yml, xml, php, or annotation) [annotation]: yml(这里我用的是yml,果然到了下面步骤出错了,需要使用annotation)

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).(自动给你创建了id)

Available types: array, simple_array, json_array, object,
boolean, integer, smallint, bigint, string, text, datetime, datetimetz,
date, time, decimal, float, binary, blob, guid.

New field name (press <return> to stop adding fields): name (接下来就是要创建字段了,以下都是创建字段)
Field type [string]: (字段类型)
Field length [255]:  (字段长度)
Is nullable [false]: (是否为空)
Unique [false]:      (是否唯一)
(直接回车,创建第二个字段)
New field name (press <return> to stop adding fields): remark
Field type [string]:
Field length [255]:
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): status
Field type [string]: boolean
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): enabled
Field type [string]: boolean
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): created
Field type [string]: datetimetz
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): modified
Field type [string]: datetimetz
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): staff
Field type [string]:
Field length [255]:
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): address
Field type [string]:
Field length [255]:
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): phone
Field type [string]:
Field length [255]:
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields): industries
Field type [string]:
Field length [255]:
Is nullable [false]:
Unique [false]:

New field name (press <return> to stop adding fields):


  Entity generation

  (成功创建了以下文件)
  created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Entity/
  created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Entity/Company.php
  created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Resources/config/doc
trine/
  created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Resources/config/doc
trine/Company.orm.yml
> Generating entity class D:\home\workspace\XXXX\src\Xin\CompanyBundle\Enti
ty\Company.php: OK!
> Generating repository class D:\home\workspace\XXXX\src\Xin\CompanyBundle\
Repository\CompanyRepository.php: OK!
> Generating mapping file D:\home\workspace\XXXX\src\Xin\CompanyBundle\Reso
urces\config\doctrine\Company.orm.yml: OK!


  Everything is OK! Now get to work :).

 

采用注解annotation生成的实体如下

<?php

namespace Xin\CompanyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Company
 *
 * @ORM\Table(name="company")
 * @ORM\Entity(repositoryClass="Xin\CompanyBundle\Repository\CompanyRepository")
 */
class Company
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="remark", type="string", length=255)
     */
    private $remark;

    /**
     * @var bool
     *
     * @ORM\Column(name="status", type="boolean")
     */
    private $status;

    /**
     * @var bool
     *
     * @ORM\Column(name="enabled", type="boolean")
     */
    private $enabled;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created", type="datetime")
     */
    private $created;

    /**
     * @var string
     *
     * @ORM\Column(name="address", type="string", length=255)
     */
    private $address;

    /**
     * @var string
     *
     * @ORM\Column(name="phone", type="string", length=255)
     */
    private $phone;

    /**
     * @var string
     *
     * @ORM\Column(name="industries", type="string", length=255)
     */
    private $industries;

    /**
     * @var string
     *
     * @ORM\Column(name="staff", type="string", length=255)
     */
    private $staff;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Company
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set remark
     *
     * @param string $remark
     *
     * @return Company
     */
    public function setRemark($remark)
    {
        $this->remark = $remark;

        return $this;
    }

    /**
     * Get remark
     *
     * @return string
     */
    public function getRemark()
    {
        return $this->remark;
    }

    /**
     * Set status
     *
     * @param boolean $status
     *
     * @return Company
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return bool
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set enabled
     *
     * @param boolean $enabled
     *
     * @return Company
     */
    public function setEnabled($enabled)
    {
        $this->enabled = $enabled;

        return $this;
    }

    /**
     * Get enabled
     *
     * @return bool
     */
    public function getEnabled()
    {
        return $this->enabled;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return Company
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

    /**
     * Get created
     *
     * @return \DateTime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set address
     *
     * @param string $address
     *
     * @return Company
     */
    public function setAddress($address)
    {
        $this->address = $address;

        return $this;
    }

    /**
     * Get address
     *
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * Set phone
     *
     * @param string $phone
     *
     * @return Company
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;

        return $this;
    }

    /**
     * Get phone
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * Set industries
     *
     * @param string $industries
     *
     * @return Company
     */
    public function setIndustries($industries)
    {
        $this->industries = $industries;

        return $this;
    }

    /**
     * Get industries
     *
     * @return string
     */
    public function getIndustries()
    {
        return $this->industries;
    }

    /**
     * Set staff
     *
     * @param string $staff
     *
     * @return Company
     */
    public function setStaff($staff)
    {
        $this->staff = $staff;

        return $this;
    }

    /**
     * Get staff
     *
     * @return string
     */
    public function getStaff()
    {
        return $this->staff;
    }
}

 

好了实体创建完了,(但是如何用命令生成带有关联关系的实体呢?我还不知道,以后再说,接下来就要写crud了吧)

创建entity之后,你应该使用以下命令来验证映射(mappings):

 $ php bin/console doctrine:schema:validate
运行结果:
$  php bin/console doctrine:schema:validate
[Mapping]  OK - The mapping files are correct.
[Database] FAIL - The database schema is not in sync with the current mapping fi
le.

6 , 接下来就要生成数据库表了:

$ php bin/console doctrine:schema:update --force
Updating database schema...
Database schema updated successfully! "3" queries were executed

 看了一下数据库果然生成了一张company表,中间的映射关系还有没有呢,还不知道怎么弄先这样;

7,这时候应该写crud了吧,试试;

(中间会有交互过程,如中文注视)

$ php bin/console generate:doctrine:crud


  Welcome to the Doctrine2 CRUD generator



This command helps you generate CRUD controllers and templates.

First, give the name of the existing entity for which you want to generate a CRUD
(use the shortcut notation like AcmeBlogBundle:Post)(例如这样写)

The Entity shortcut name: XinCompanyBundle:Company (我的Bundle写法,这次就知道怎么写名字了,新建实体的时候已经用过了)

By default, the generator creates two actions: list and show.
You can also ask it to generate "write" actions: new, update, and delete.

Do you want to generate the "write" actions [no]? yes(其实以下所有交互你都可以默认回车,这里如果选择no,那么就不会生成创建,编辑的方法了,
如果你不需要更改的话,我选择 yes,直接全部生成出来) Determine the format to use for the generated CRUD. Configuration format (yml, xml, php, or annotation) [annotation]: (还是直接使用annotation注解吧) Determine the routes prefix (all the routes will be "mounted" under this prefix: /prefix/, /prefix/new, ...). Routes prefix [/company]:(这里要你输入路由,我默认的,其实默认就可以了,默认的还比较规范) Summary before generation You are going to generate a CRUD controller for "XinCompanyBundle:Company" using the "yml" format. Do you confirm generation [yes]?(回车) CRUD generation (创建了这么多文件) created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Controller//CompanyController.php created D:\home\workspace\XXXX\app/Resources/views/company/ created D:\home\workspace\XXXX\app/Resources/views/company/index.html.twig created D:\home\workspace\XXXX\app/Resources/views/company/show.html.twig created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Tests/Controller/ created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Tests/Controller//CompanyControllerTest.php created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Resources/config/routing/ created D:\home\workspace\XXXX\src\Xin\CompanyBundle/Resources/config/routing/company.yml Generating the CRUD code: OK Updating the routing: Confirm automatic update of the Routing [yes]? Importing the CRUD routes: created D:\home\workspace\quanxinxi\src\Xin\CompanyBundle/Resources/config/routing.yml
(这就报错了,一定就是我创建Bundle的时候选择了annotation 而创建实体的时候选择了yml,对就是这里出错了) [ERROR] The bundle's "Resources/config/routing.yml" file cannot be importedfrom "app/config/routing.yml" because the "XinCompanyBundle" bundle is already
imported.
Make sure you are not using two different configuration/routing formats in the same bundle because it won't work. OK Everything is OK! Now get to work :).

 

这个错误;(需要修改系统中的php.ini)

datefmt_create: no such time zone: 'utc': U_ILLEGAL_ARGUMENT_ERROR
500 Internal Server Error - InvalidOptionsException 

 问题解决如下

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = "PRC" 找到这一行,去掉前面的;号,然后改为="PRC"

 

 到现在为止CRUD已经生成了;不过遗憾的是views生成目录放在了app/Resources目录下了,所以需要手工改一下目录;I

移动前

 

如图移动后

 

 现在运行的话,那么bug就出来了

如下:

 

Unable to find template "company/index.html.twig" (looked into: D:\home\workspace\XXXX\app/Resources/views, 
D:\home\workspace\XXXX\vendor\symfony\symfony\src\Symfony\Bridge\Twig/Resources/views/Form). 500 Internal Server Error - InvalidArgumentException 1 linked Exception: Twig_Error_Loader »

 这个bug 是说找不到模板了,不要着急,首先找到你的controller,先看第一个方法中代码如下
(注释就是更改方法,那么show,edit,new,,,,,,方法的render都改成如下注释中的格式就ok了)

    /**
     * Lists all company entities.
     *
     * @Route("/", name="company_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $companies = $em->getRepository('XinCompanyBundle:Company')->findAll();

        return $this->render('company/index.html.twig',//就是这里你改成   XXXBundle:实体名:index.html.twig(我的XinCompanyBundle:Company:index.html.twig,
                                                              其中Xin是你的项目名
)
       array( 'companies' => $companies, )); }

 

好了CRUD也写好了,那么我又给我的Bundle添加了一个布局模板,如下:

 


代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}企业管理{% endblock %}</title>
        {% block stylesheets %}{% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
        {% block header %}{% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
        {% block javascripts %}{% endblock %}
        {% block footer %}{% endblock %}
    </body>
</html>

 

这样的话在CRUD的页面就可以继承这个页面了

代码如下(如index.html.twig):

{% extends 'XinCompanyBundle::company.layout.html.twig' %}    --继承 bundle名称::模板名称

{% block body %}
    <h1>Companies list</h1>

    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Address</th>
                <th>Industries</th>
                <th>Member</th>
                <th>Remark</th>
                <th>Status</th>
                <th>Enabled</th>
                <th>Created</th>
                <th>Modified</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        {% for company in companies %}
            <tr>
                <td><a href="{{ path('company_show', { 'id': company.id }) }}">{{ company.id }}</a></td>
                <td>{{ company.name }}</td>
                <td>{{ company.phone }}</td>
                <td>{{ company.address }}</td>
                <td>{{ company.industries }}</td>
                <td>{{ company.member }}</td>
                <td>{{ company.remark }}</td>
                <td>{% if company.status %}Yes{% else %}No{% endif %}</td>
                <td>{% if company.enabled %}Yes{% else %}No{% endif %}</td>
                <td>{% if company.created %}{{ company.created|date('Y-m-d H:i:s') }}{% endif %}</td>
                <td>{% if company.modified %}{{ company.modified|date('Y-m-d H:i:s') }}{% endif %}</td>
                <td>
                    <ul>
                        <li>
                            <a href="{{ path('company_show', { 'id': company.id }) }}">show</a>
                        </li>
                        <li>
                            <a href="{{ path('company_edit', { 'id': company.id }) }}">edit</a>
                        </li>
                    </ul>
                </td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

    <ul>
        <li>
            <a href="{{ path('company_new') }}">Create a new company</a>
        </li>
    </ul>
{% endblock %}

 

ok 今天就写到这里,明天继续做任务

-------------------------------------------------------------------------------------------------------------------〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉〉

今天1月11号

今天登陆系统发现主页不见了;好吧路有出错了,把/company加到app/config/routing.yml中;ok可以了。

 

今天目标就是把包结构整理好,到现在为止前面的设计,代码等觉得都不是规整,既然做项目就要规范一些,

1:调整代码结构,2:把用户,权限,登陆都写好;

开始:我现在写用户,因为这里比较急用;

 1〉我先要安装一个Bundle(至于为什么,现在我也不知道)

 命令如下:

 composer require friendsofsymfony/user-bundle "~2.0@dev"

总是给我报这个错!!!!!!!!!!!!!!!!!!

Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Updating the "app/config/parameters.yml" file
Some parameters are missing. Please provide them.
database_name (symfony): 总是要我输入,最后终于找到哪里没有配置了,  parameters.yml.dist,这个文件我竟然没有配置数据库信息;

 当然你还有不时地清理一下缓存,命令如下

$ php bin/console cache:clear # 清除缓存

 最终安装上User那个Bundle

运行如下:

$ composer require friendsofsymfony/user-bundle "~2.0@dev"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Removing twig/twig (v1.30.0)
  - Installing twig/twig (v1.28.2)
    Loading from cache

  - Removing doctrine/orm (v2.5.6)
  - Installing doctrine/orm (v2.5.5)
    Loading from cache

  - Removing doctrine/doctrine-bundle (1.6.6)
  - Installing doctrine/doctrine-bundle (1.6.4)
    Loading from cache

  - Removing swiftmailer/swiftmailer (v5.4.5)
  - Installing swiftmailer/swiftmailer (v5.4.4)
    Loading from cache

  - Removing symfony/swiftmailer-bundle (v2.4.2)
  - Installing symfony/swiftmailer-bundle (v2.4.0)
    Loading from cache

  - Removing symfony/monolog-bundle (v3.0.3)
  - Installing symfony/monolog-bundle (3.0.1)
    Loading from cache

  - Removing sensio/distribution-bundle (v5.0.18)
  - Installing sensio/distribution-bundle (v5.0.15)
    Loading from cache

  - Removing sensio/framework-extra-bundle (v3.0.19)
  - Installing sensio/framework-extra-bundle (v3.0.16)
    Loading from cache

  - Installing friendsofsymfony/user-bundle (dev-master e889095)
    Cloning e889095060584db187784d4b6e2d1efcff2de242
    Failed to download friendsofsymfony/user-bundle from source: Failed to clone
 https://github.com/FriendsOfSymfony/FOSUserBundle.git via https, ssh protocols,
 aborting.

- https://github.com/FriendsOfSymfony/FOSUserBundle.git
  Cloning into 'D:\home\workspace\XXXX\vendor\friendsofsymfony\user-bundle'
...
  fatal: unable to access 'https://github.com/FriendsOfSymfony/FOSUserBundle.git
/': Failed to connect to github.com port 443: Timed out

- git@github.com:FriendsOfSymfony/FOSUserBundle.git
  Cloning into 'D:\home\workspace\XXXX\vendor\friendsofsymfony\user-bundle'
...
  ssh: connect to host github.com port 22: Bad file number
  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights
  and the repository exists.

    Now trying to download from dist
  - Installing friendsofsymfony/user-bundle (dev-master e889095)
    Loading from cache

Writing lock file
Generating autoload files
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Updating the "app/config/parameters.yml" file
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

 // Clearing the cache for the dev environment with debug
 // true

 [OK] Cache for the "dev" environment (debug=true) was successfully cleared.

> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::installAssets

 Trying to install assets as relative symbolic links.

 --------- ------------- ----------------
            Bundle        Method / Error
 --------- ------------- ----------------
  WARNING   XinXiBundle   copy
 --------- ------------- ----------------

 ! [NOTE] Some assets were installed via copy. If you make changes to these
 !        assets you have to run this command again.

 [OK] All assets were successfully installed.

> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::installRequirementsFi
le
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::prepareDeploymentTarg
et

 以上只是下载了UserBundle 接下来就要使用它了;一系列的添加配置,如下:。。。。。。。。。

先分享一下别人的博客里的关于Symfony包目录结构把http://www.cnblogs.com/szuyuan/p/4015402.html

2 〉注册Bundle,

这个的话就在app/AppKernel.php里面添加 new 。。。。。
如下:

public function registerBundles()
{
    $bundles = array(
        // ...
        new FOS\UserBundle\FOSUserBundle(),
    );
}
3〉配置config.yml文件添加
 
如果报错如下那么就应该,配置config.yml文件添加
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]

The child node "db_driver" at path "fos_user" must be configured.

 

配置如下: 添加上就可以了

fos_user:
db_driver: orm
firewall_name: main


如果在报这个错误如下
 [Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]

 The child node "user_class" at path "fos_user" must be configured.

 那就再添加上user_class

 





4〉FOSUserBundle 要求我们创建一个继承自 FOS\UserBundle\Model\User 的用户类;

 

 

 

 

今天是1月13号,以上添加Bundle的过程,我打算重新来一遍,记录的先留着吧,下面我开始重新添加;

一边记录过程一边上传代码https://github.com/TuringTD/Symfony

如果感兴趣可以加入我Symfony群进行交流182983780,里面技术大牛可以帮你解决问题 的

1:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



 

posted @ 2017-01-09 09:41  ldp.im  阅读(1690)  评论(0编辑  收藏  举报