如果需要这个样例程序的全部源代码,可以访问 这里 ,或者通过下面的方式获取源代码:
$git clone https://github.com/saharabear/symfony-sample.git
项目初始化
首先,需要你在自己的电脑中安装php环境并安装git.这方面的内容属于基础内容,网络上有大量的教程,在这里就不多介绍了,不过要提示的一点是:php从5.4开始, 已经内置了测试用服务器,symfony也拥抱了这个由php内置的服务器,只需要在命令行中使用$php app/console server:run 就可以 启动基于symfony框架的php程序进行测试,因此不必要使用xampp这一类复杂的集成环境,直接安装php并保证在命令行下可以执行php命令就可以了。
然后,我们需要建立一个新的目录,名字叫symfony-sample,symfony使用一个叫composer的程序管理各种类库的依赖关系,因此如果你的机器上 安装了composer,就可以直接跳过这一步,如果没有安装,可以用下面的命令安装最新版本的composer.
$cd symfony-sample$curl -ss https://getcomposer.org/installer | php
如果希望了解更多关于composer的信息,可以参考这个网站。
安装完成composer后,我们可以开始安装当前最新版本的symfony2.6.0
复制代码 代码如下:
$php composer.phar create-project symfony/framework-standard-edition mysampleproject/ 2.6.0
安装过程中,需要填写数据库等信息,在这个例子中,我们会使用mysql数据库,因此你可以一路按回车键,先不要关心这一切配置应该如何填写。反正 symfony会在安装成功后,生成一个配置文件,叫app/config/parameters.yml,下面我会提供一个parameters.yml文件的 内容样本,只要复制进去就可以了,先不必关注这么多细节。
刚才创建mysampleproject以后,在symfony-sample目录下生成了mysampleproject目录,我习惯于将程序放在项目的根目录下,因此执行下面的几个命令, 就可以把项目从symfony-sample/mysampleproject目录中,移到symfony-sample目录中
$mv mysampleproject/* ./$rm -rf mysampleproject
理论上来讲,我们已经完成了symfony项目的创建,不过刚才提到的parameters.yml文件还没有解释。这个parameters.yml是symfony的全局配置文件, 无论是数据库配置信息还是其他的各种配置,都可以放在这个文件中。下面是我们需要使用的测试用的parameters.yml,记得把最后一行的值修改为一个随机值
# this file is auto-generated during the composer installparameters: database_driver: pdo_mysql database_host: localhost database_port: 3306 database_name: symfony database_user: root database_password: root mailer_transport: smtp mailer_host: localhost mailer_user: null mailer_password: null locale: en secret: changethislineasyouwish_ioiuqwoieru
直接用这段,替换掉app/config/parameters.yml文件中的内容,然后编辑app/config/config.yml,找到下面几行,把最后一行添加进去并保存。
driver: %database_driver%host: %database_host%port: %database_port%dbname: %database_name%user: %database_user%password: %database_password%charset: utf8path: %database_path%
好了,这样我们就完成了基本的symfony程序的配置,你现在有了一个配置好了数据库,邮件发送器,日志系统的基本程序原型。下面,我们就开始编写自己的symfony程序。
建立bundle
先说一下什么是bundle。symfony是以di为核心的,可能你不知道什么是di,没关系,这不重要,你可以把symfony的di理解成为一个功能池,把程序中的所有功能都做成bundle,或者你把bundle理解成一组php文件组合而成的程序就可以。 比如用户注册,登录功能做成一个bundle,你也可以把一个论坛的发帖回贴功能做成一个bundle,自然也可以把文章管理做成一个bundle,然后用一个bundle去调用和配置不同的bundle,那么你就可以把网站组装起来了,而你写的各种bundle,在其他的应用程序中还可以继续复用,这样写的bundle越多,可复用性就越强,制作新项目的时候也越有利。
我们现在就来建立自己的bundle.在命令行中,使用命令:
$php app/console generate:bundlebundle namespace: symfony/bundle/samplebundlebundle name [symfonysamplebundle]:target directory [/home/saharabear/workspace/symfony-sample/src]:configuration format (yml, xml, php, or annotation): ymldo you want to generate the whole directory structure [no]? yesdo you confirm generation [yes]? yesgenerating the bundle code: okchecking that the bundle is autoloaded: okconfirm automatic update of your kernel [yes]? yesenabling the bundle inside the kernel: okconfirm automatic update of the routing [yes]? yes
这样就成功建立了我们的bundle,名字叫symfonysamplebundle,我们使用的bundle namespace是symfony/bundle/samplebundle,这是一种约定,我们还可以建立其他的bundle,比如symfony/bundle/postbundle, 或者symfony/bundle/articlebundle,而对应的bundle name就分别是symfonypostbundle或者symfonyarticlebundle。你也可以自己建立这几个bundle,这并不会影响当前我们的教程。
对了,在我们建立的bundle中,分别会生成下面几个目录:
① entity:这个目录并不是必须的,很多情况下只有在生成实体的时候才会生成,放置模型,也就是mvc中的m
② controller:这个目录会生成defaultcontroller.php,你可以在这里建立自己的controller控制器,也就是mvc中的c
③ resources:这个目录下面还有子目录,其中views放置的是模板,也就是mvc中的v,而public放置的是静态文件,比如js, css, images等等
④ tests:放置单元测试与集成测试的代码,在这个样例程序中暂时不需要
⑤ dependencyinjection:与di相关的目录,暂时也不需要去了解
⑥ symfonysamplebundle.php:当前这个bundle的定义文件
更多细节可以去阅读symfony 的官方文档,而当前的重点是把这个symfony的样例程序运行起来。
设计实体
在mvc的设计理念中,m是最重要的,因为m表达的内容是业务逻辑。我觉得如果这个地方往深入去探讨,会一直探讨到富血模型或者贫血模型,不过目前在这个教程中根本 不需要考虑这么多,你只需要知道实体就是mvc中的m,用于表达业务逻辑。比如说,我们要开发一个文章管理的系统,那么文章本身就代表的业务逻辑。比如,我们的文章要有 标题,内容,作者,那么这三项就属于业务逻辑,而标题不能够为空,不能超过200长度,内容不能为空,作者却是可以为空的,这些也属于业务逻辑。同时,这个文章需要被 存储起来,比如存储到数据库中,那么这个m就应该能够映射到数据库的表中。我们把这个m,叫实体。
还是少说废话,直接上代码。那么如何建立实体呢?当然不是从头一点一点地写,而是直接用下面的命令生成:
$php app/console generate:doctrine:entitywelcome to the doctrine2 entity generatorthis 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.the entity shortcut name: symfonysamplebundle:articledetermine the format to use for the mapping information.configuration format (yml, xml, php, or annotation) [annotation]:ymlinstead of starting with a blank entity, you can add some fields now.note that the primary key will be added automatically (named id).available types: array, simple_array, json_array, object,boolean, integer, smallint, bigint, string, text, datetime, datetimetz,date, time, decimal, float, blob, guid.new field name (press to stop adding fields): titlefield type [string]:field length [255]: 200new field name (press to stop adding fields): contentfield type [string]: textnew field name (press to stop adding fields): authorfield type [string]:field length [255]: 20new field name (press to stop adding fields):do you want to generate an empty repository class [no]? yessummary before generationyou are going to generate a symfonysamplebundle:article doctrine2 entityusing the yml format.do you confirm generation [yes]? yesentity generationgenerating the entity code: okyou can now start using the generated code!
经过这些命令,你会发现在entity中建立了新的文件article.php,代码如下:
namespace symfony\bundle\samplebundle\entity;use doctrine\orm\mapping as orm;/** * article * * @orm\table() * @orm\entity(repositoryclass=symfony\bundle\samplebundle\entity\articlerepository) */class article{ /** * @var integer * * @orm\column(name=id, type=integer) * @orm\id * @orm\generatedvalue(strategy=auto) */ private $id; /** * @var string * * @orm\column(name=title, type=string, length=200) */ private $title; /** * @var string * * @orm\column(name=content, type=text) */ private $content; /** * @var string * * @orm\column(name=author, type=string, length=20) */ private $author; /** * get id * * @return integer */ public function getid() { return $this->id; } /** * set title * * @param string $title * @return article */ public function settitle($title) { $this->title = $title; return $this; } /** * get title * * @return string */ public function gettitle() { return $this->title; } /** * set content * * @param string $content * @return article */ public function setcontent($content) { $this->content = $content; return $this; } /** * get content * * @return string */ public function getcontent() { return $this->content; } /** * set author * * @param string $author * @return article */ public function setauthor($author) { $this->author = $author; return $this; } /** * get author * * @return string */ public function getauthor() { return $this->author; }}
你可以一行不改地使用这些代码。这时候我们再来做几个神奇的操作:
复制代码 代码如下:
$php app/console doctrine:schema:update --force
这个操作,已经帮助你通过article.php建立了数据库和数据表,你不需要自己操作这个过程,下面我们还会对article.php进行改造,而到时候只需要重新 执行上面的这个操作,symfony会帮助你自动修改数据库的表结构。
添加约束
上面我们创建了article.php,既然这个实体代表了具体的业务逻辑,因此我们要考虑几个现实的问题:
1. 用户必须填写标题和内容
2. 用户填写的标题不能超过200个字
3. 用户可以不填写作者
这些就属于业务逻辑,而我们可以修改article.php如下,以增加相应的业务逻辑的约束:
namespace symfony\bundle\samplebundle\entity;use doctrine\orm\mapping as orm;use symfony\component\validator\constraints as assert;/** * article * * @orm\table() * @orm\entity(repositoryclass=symfony\bundle\samplebundle\entity\articlerepository) */class article{ /** * @var integer * * @orm\column(name=id, type=integer) * @orm\id * @orm\generatedvalue(strategy=auto) */ private $id; /** * @var string * @assert\notblank(message=标题不可为空) * @assert\length( * max=200, * maxmessage=标题不能超过200个字 * ) * @orm\column(name=title, type=string, length=200) */ private $title; /** * @var string * * @assert\notblank(message=文章内容不可为空) * @orm\column(name=content, type=text) */ private $content; /** * @var string * * @orm\column(name=author, type=string, length=20,nullable=true) */ private $author; /** * get id * * @return integer */ public function getid() { return $this->id; } /** * set title * * @param string $title * @return article */ public function settitle($title) { $this->title = $title; return $this; } /** * get title * * @return string */ public function gettitle() { return $this->title; } /** * set content * * @param string $content * @return article */ public function setcontent($content) { $this->content = $content; return $this; } /** * get content * * @return string */ public function getcontent() { return $this->content; } /** * set author * * @param string $author * @return article */ public function setauthor($author) { $this->author = $author; return $this; } /** * get author * * @return string */ public function getauthor() { return $this->author; }}
然后执行同步数据库的操作:
$ php app/console doctrine:schema:update --forceupdating database schema...database schema updated successfully! 1 queries were executed
增删改查
好了,我们来做一个针对文章的增删改查操作。首先请执行下面的命令:
$ php app/console generate:doctrine:crud welcome to the doctrine2 crud generatorthis command helps you generate crud controllers and templates.first, you need to give the entity for which you want to generate a crud.you can give an entity that does not exist yet and the wizard will helpyou defining it.you must use the shortcut notation like acmeblogbundle:post.the entity shortcut name: symfonysamplebundle:articleby 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]? yesdetermine the format to use for the generated crud.configuration format (yml, xml, php, or annotation) [annotation]: ymldetermine the routes prefix (all the routes will be mounted under thisprefix: /prefix/, /prefix/new, ...).routes prefix [/article]: /article summary before generationyou are going to generate a crud controller for symfonysamplebundle:articleusing the yml format.do you confirm generation [yes]? yes crud generationgenerating the crud code: okgenerating the form code: ok you can now start using the generated code!
然后请编辑defaultcontroller.php中的indexaction如下:
/** * @route(/,name=welcome) * @template() */public function indexaction(){ return array();}
编辑resource/views/default/index.html.twig内容如下:
文章管理
让我们看看神奇的事情,启动内置的测试服务器:
$php app/console server:run
好了,我们已经完成了这十分钟的博客,一切的代码都在controller/articlecontroller.php,form/articletype.php,resource/views/article/*.html.twig中,我们已经完成了最基本的文章管理功能。当然在你熟悉symfony以后,未必需要完全依靠symfony帮你生成这些增删改查操作,可是起码symfony用一个命令让一切都先运行起来了,这不就是我们所要的原型吗?
本文永久地址:http://blog.it985.com/5133.html
本文出自 it985博客 ,转载时请注明出处及相应链接。
更多关于php框架相关内容感兴趣的读者可查看本站专题:《php优秀开发框架总结》,《codeigniter入门教程》,《ci(codeigniter)框架进阶教程》,《yii框架入门及常用技巧总结》及《thinkphp入门教程》
希望本文所述对大家基于symfony框架的php程序设计有所帮助。
