Symfony is a powerful PHP-based Web development framework. Here we use ten minutes to make a simple Anyone who is not familiar with Symfony can complete their first Symfony program through this tutorial.
If you need the full source code of this sample program, you can visit here , or obtain the source code through the following method:
$git clone https://github.com/saharabear/symfony-sample.git
Project initialization
First of all, you need to install the PHP environment and git on your computer. This content is basic content. There are a lot of tutorials on the Internet, so I won’t introduce them here. But one thing to note is: PHP Starting from 5.4, a test server has been built in. Symfony has also embraced this server built into PHP. You only need to use $php app/console server:run in the command line to start a PHP program based on the Symfony framework for testing. Therefore There is no need to use a complex integrated environment such as XAMPP. Just install PHP directly and ensure that the php command can be executed on the command line.
Then, we need to create a new directory called symfony-sample. Symfony uses a program called composer to manage the dependencies of various class libraries, so if composer is installed on your machine, you can skip it directly. In this step, if it is not installed, you can use the following command to install the latest version of composer.
$cd symfony-sample $curl -sS https://getcomposer.org/installer | php
If you want to know more about composer, you can refer to this website.
After installing composer, we can start installing the latest version of Symfony2.6.0
Copy code The code is as follows: $php composer.phar create-project symfony/framework-standard-edition mysampleproject/ 2.6.0
During the installation process, you need to fill in the database and other information. In this example, we will use the mysql database, so you can press the Enter key all the way. Don’t worry about how to fill in all the configurations. Anyway, after successful installation, Symfony will generate a configuration file called app/config/parameters.yml. Below I will provide a sample content of the parameters.yml file. Just copy it into it. There is no need to pay attention to so many details.
After creating mysampleproject just now, the mysampleproject directory was generated under the symfony-sample directory. I am used to placing the program in the root directory of the project, so by executing the following commands, the project can be moved from symfony-sample/mysampleproject directory, move to the symfony-sample directory
$mv mysampleproject/* ./ $rm -rf mysampleproject
Theoretically, we have completed the creation of the Symfony project, but the parameters.yml file just mentioned has not yet been explained. This parameters.yml is the global configuration file of Symfony. Whether it is database configuration information or various other configurations, it can be placed in this file. Below is the parameters.yml we need to use for testing. Remember to change the value in the last line to a random value
# This file is auto-generated during the composer install parameters: 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
Use this paragraph directly to replace the content in the app/config/parameters.yml file, then edit app/config/config.yml, find the following lines, add the last line and save it.
driver: "%database_driver%" host: "%database_host%" port: "%database_port%" dbname: "%database_name%" user: "%database_user%" password: "%database_password%" charset: UTF8 path: "%database_path%"
Okay, so we have completed the configuration of the basic Symfony program. You now have a basic program prototype with a database, email sender, and logging system configured. Next, we start writing our own Symfony program.
Create Bundle
First, let’s talk about what a Bundle is. Symfony is based on DI. Maybe you don’t know what DI is. It doesn’t matter. It’s not important. You can understand Symfony’s DI as a function pool and make all functions in the program into Bundles. Or you can understand Bundle. It can be a program composed of a set of php files. For example, user registration and login functions are made into a Bundle. You can also make a forum's post and reply function into a Bundle. Naturally, you can also make article management into a Bundle, and then use one Bundle to call and configure different Bundles. Then you can assemble the website, and the various Bundles you write can continue to be reused in other applications. The more Bundles you write, the stronger the reusability. When making new projects The more advantageous it is.
We will create our own Bundle now. In the command line, use the command:
$php app/console generate:bundle Bundle namespace: Symfony/Bundle/SampleBundle Bundle name [SymfonySampleBundle]: Target directory [/home/saharabear/workspace/symfony-sample/src]: Configuration format (yml, xml, php, or annotation): yml Do you want to generate the whole directory structure [no]? yes Do you confirm generation [yes]? yes Generating the bundle code: OK Checking that the bundle is autoloaded: OK Confirm automatic update of your Kernel [yes]? yes Enabling the bundle inside the Kernel: OK Confirm automatic update of the Routing [yes]? yes
In this way, our Bundle is successfully created, named SymfonySampleBundle. The Bundle namespace we use is Symfony/Bundle/SampleBundle. This is a convention. We can also create other Bundles, such as Symfony/Bundle/PostBundle, or Symfony/Bundle/ArticleBundle, and the corresponding Bundle names are SymfonyPostBundle or SymfonyArticleBundle respectively. You can also create these Bundles yourself, which will not affect our current tutorial.
By the way, in the Bundle we created, the following directories will be generated:
① 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: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. The Entity shortcut name: SymfonySampleBundle:Article Determine the format to use for the mapping information. Configuration format (yml, xml, php, or annotation) [annotation]:yml Instead 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): title Field type [string]: Field length [255]: 200 New field name (press to stop adding fields): content Field type [string]: text New field name (press to stop adding fields): author Field type [string]: Field length [255]: 20 New field name (press to stop adding fields): Do you want to generate an empty repository class [no]? yes Summary before generation You are going to generate a "SymfonySampleBundle:Article" Doctrine2 entity using the "yml" format. Do you confirm generation [yes]? yes Entity generation Generating the entity code: OK You 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 --force Updating database schema... Database schema updated successfully! "1" queries were executed
增删改查
好了,我们来做一个针对文章的增删改查操作。首先请执行下面的命令:
$ php app/console generate:doctrine:crud Welcome to the Doctrine2 CRUD generator This 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 help you defining it. You must use the shortcut notation like AcmeBlogBundle:Post. The Entity shortcut name: SymfonySampleBundle:Article 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 Determine the format to use for the generated CRUD. Configuration format (yml, xml, php, or annotation) [annotation]: yml Determine the routes prefix (all the routes will be "mounted" under this prefix: /prefix/, /prefix/new, ...). Routes prefix [/article]: /article Summary before generation You are going to generate a CRUD controller for "SymfonySampleBundle:Article" using the "yml" format. Do you confirm generation [yes]? yes CRUD generation Generating the CRUD code: OK Generating 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内容如下:
<a href="{{path('article')}}">文章管理</a>
让我们看看神奇的事情,启动内置的测试服务器:
$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程序设计有所帮助。