php_Symfony_項目實戰全過程記錄

爲了你們方便交流加Symfony技術交流羣, 182983780javascript

 

微信公衆號:php

 

今天是2017年1月8號,正式接收到一個Symfony 的項目,準備全程記錄遇到的問題及解決方法,以前被通知學習該框架,只是一直沒有機會作項目,今天終於能夠作了,但願2017把Symfony學的能會使用,可以解決基本問題,可以獨立新建項目。。。。。2017開始了。。。。。。。。html

-------------------------------------------------------------------------------------------------java

1月8號,更新代碼,因爲有兩三個月沒有看symfony了,上來就遇到了以前的問題,幸虧遇到過(如下XXX表明項目名稱)哈哈node

1:更新代碼。。。。。git

2:跑項目github

問題以下:sql

$ 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

解釋:沒有安裝依賴包mongodb

 

問題解決:執行$ php cocomposer.json  composer.lock  composer.pharshell

 

運行後以下:

 

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:

相關文章
相關標籤/搜索