Symfony Learning 10-minute Introductory Classic Tutorial _php example

Source: Internet
Author: User
Tags assert generator install php php framework codeigniter composer install git clone

Symfony is a powerful PHP based Web development framework, where we use 10 minutes to do a simple deletion and modification procedures, anyone unfamiliar with Symfony can complete their first Symfony program through this tutorial.

If you need the full source code for this sample program, you can access it here, or get the source code in the following way:

$git Clone Https://

Project initialization

First of all, you need to install the PHP environment on your own computer and install Git. This content is the basic content, the network has a lot of tutorials, here is not much introduced, but to hint is: PHP starting from 5.4, has built a test server, Symfony also embraced this PHP-built server, using $php app/console server:run on the command line to start testing the Symfony-based PHP program, so it is unnecessary to use XAMPP, a complex integration environment, Install PHP directly and make sure that you can execute the PHP command at the command line.

Then, we need to create a new directory named Symfony-sample,symfony use a program called composer to manage the dependencies of various libraries, so if you have composer installed on your machine, you can skip this step, if not installed, You can install the latest version of composer with the following command.

$CD symfony-sample
$curl-ss | php

If you want to know more about composer, you can refer to this website.

After the installation completes composer, we can begin to install the current version of the Symfony2.6.0

Copy Code code as follows:
$php Composer.phar create-project symfony/framework-standard-edition mysampleproject/2.6.0

In the installation process, you need to fill in the database information, in this example, we will use the MySQL database, so you can press the return all the way, do not care about all this configuration should be completed. Anyway Symfony will be successful after the installation, generate a configuration file, called App/config/parameters.yml, I will provide a sample of parameters.yml files, as long as the copy in on it, you do not have to pay attention to so many details.

After the Mysampleproject was created, the Mysampleproject directory was generated in the Symfony-sample directory, and I was accustomed to placing the program under the root of the project, so I executed a few commands below, You can move items from the Symfony-sample/mysampleproject directory 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 mentioned earlier has not been explained. This parameters.yml is a symfony global configuration file that can be placed in this file, whether it is database configuration information or a variety of other configurations. Here is the test parameters.yml we need to use, remember to change the last line value to a random value

# This file is auto-generated during the composer install
  Database_ Host:localhost
  Database_password: Root

Use this section directly, replace the contents of the App/config/parameters.yml file, edit the 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%"
Path:   "%database_path%"

OK, so we have completed the basic Symfony program configuration, you now have a configured database, mail transmitter, log system of the basic program prototype. Below, we begin to write our own symfony program.

Establish bundle

First of all, what is bundle. Symfony is centered on Di, maybe you don't know what di is, it's okay, it's not important, you can symfony di into a function pool, all the functions in the program are made into bundle, or you bundle a group of PHP files into a combination of the program can be. For example, user registration, login function to make a bundle, you can also post a forum posting function as a bundle, nature can also be made into a bundle article management, and then use a bundle to invoke and configure a different bundle, Then you can assemble the site, and you write a variety of bundle, in other applications can continue to reuse, so write more bundle, reusability is stronger, the more favorable when making new projects.

We're going to build our own bundle. On the command line, use the command:

$php app/console generate:bundle
bundle Namespace:symfony/bundle/samplebundle
Bundle name [ Symfonysamplebundle]:
Configuration Format (yml, XML, PHP, or annotation): Yml
do your want to generate the whole directory structure [no]? Yes do
Confirm generation [Yes]?  Yes
generating the bundle Code:ok
Checking This 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

This is the successful establishment of our Bundle, named Symfonysamplebundle, we use the Bundle namespace is Symfony/bundle/samplebundle, this is a convention, We can also create other Bundle, such as Symfony/bundle/postbundle, or symfony/bundle/articlebundle, and the corresponding Bundle Name is Symfonypostbundle or Symfonyarticlebundle respectively. You can also build these bundle yourself, which does not affect the current tutorial.

By the bundle, in our set up, the following directories will be generated:

①entity: This directory is not required, in many cases it will only be generated when the entity is generated, the placement model, which is the M in MVC
②controller: This directory generates defaultcontroller.php, where you can build your own Controller controller, which is C in MVC.
③resources: This directory also has subdirectories, where views placed is the template, that is, MVC in the V, and public placed is static files, such as JS, CSS, images and so on
④tests: The code to place unit tests and integration tests is not needed in this sample program for the time being
⑤dependencyinjection: A directory related to Di, which you don't need to know for the time being
⑥symfonysamplebundle.php: Current definition file for this bundle

More details are available to read Symfony's official documentation, and the current focus is on running the Symfony sample program.

Design Entities

In the design philosophy of MVC, M is the most important, because the content of M expression is the business logic. I think if this place goes deep into it, it's going to be about the rich blood model or the anemia model, but there's no need to think about so much in this tutorial, you just need to know that the entity is the M in MVC and is used to express business logic. For example, we want to develop an article management system, then the article itself represents the business logic. For example, our article should have title, content, author, then these three items belong to the business logic, and the title can not be empty, not more than 200 length, content can not be empty, the author is can be empty, these also belong to the business logic. At the same time, this article needs to be stored, such as stored in the database, then this m should be able to map to the database table. We call this m, the entity.

or less nonsense, directly on the code. So how do you build an entity? It's not written from scratch, of course, but it's generated directly with the following command: 1.1.

$php App/console generate:doctrine:entity Welcome to the Doctrine2 entity generator This command helps you generate DOCTR
Ine2 entities.
Need to give the entity name for you want to generate.
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 would be added automatically (named ID). Available Types:array, Simple_array, Json_array, Object, Boolean, Integer, smallint, bigint, String, Text, datetime, date
Timetz, date, time, decimal, float, blob, GUID. New field name (press to stop adding fields): Title field type [string]: Field length [255]: The new field name (Press to Stop adding fields): Content Field Type [string]: Text New Field name (press to stop adding fields): Author field type [St Ring]: FieLD length [255]: New field name (Press to stop adding fields): Does you want to generate a empty class [No]? Yes Summary before generation you are going to generate a "symfonysamplebundle:article" Doctrine2 entity using the "YML" F
Ormat. Do you confirm generation [Yes]?

 Yes Entity generation generating the Entity Code:ok you can now start using the generated code!

After these commands, you will find that you have created a new file article.php in entity, the code is as follows:

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 \generat
  Edvalue (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;


You can use the code in one line without changing it. Now we're going to do a few more magical things:

Copy Code code as follows:
$php app/console doctrine:schema:update--force

This operation has helped you build the database and datasheet through article.php, you do not need to operate the process yourself, we will also transform the article.php, and then only need to rerun the above operation, Symfony will help you automatically modify the database's table structure.

Add constraint

We created the article.php, and since this entity represents the specific business logic, we need to consider several practical issues:

1. The user must fill in the title and the content
2. The user fills in the title cannot exceed 200 words
3. Users can not fill out the author

These are business logic, and we can modify article.php as follows to increase the constraints of the corresponding business logic:

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 \generat
  Edvalue (strategy= "AUTO") * * private $id; /** * @var String * @Assert \notblank (message= "title is not Nullable") * @Assert \length (* max=200, * maxmessage= "title does not exceed
  200 words "*" * @ORM \column (name= "title", Type= "string", length=200) * * Private $title;
  /** * @var String * * @Assert \notblank (message= "article content is not nullable") * @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;


Then perform the synchronization database operation:

$ php app/console doctrine:schema:update--force
Updating database schema ...
Database Schema updated successfully! "1" Queries were executed

Check and delete and change

All right, let's do an article on the additions and deletions to check the operation. First, execute the following command:

$ php app/console Generate:doctrine:crud Welcome to the Doctrine2 crud Generator This command helps you generate CRUD Co
Ntrollers and templates.
The need to give of the entity for which your want to generate a CRUD.
You can give a entity that does not exist yet and the wizard to help you defining it.
Must use the shortcut notation like acmeblogbundle:post.
The Entity shortcut name:SymfonySampleBundle:Article by default, the generator creates two actions:list and show.
can also ask it to generate "write" actions:new, update, and delete. Do your want to generate the "write" actions [No]?
Yes determine the format to the generated CRUD. Configuration format (yml, XML, PHP, or annotation) [annotation]: Yml Determine the routes prefix (all the routes would be
"Mounted" under this prefix:/prefix/,/prefix/new, ...). Routes prefix [/article]:/article Summary before generation you are going to generate a CRUD controller for "Symfonysamp Lebundle: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


Then please edit the indexaction in defaultcontroller.php as follows:

 * @Route ("/", name= "Welcome")
 * @Template ()/Public
function indexaction ()
  return Array ();

The contents of the edited Resource/views/default/index.html.twig are as follows:

<a href= "{{path (' article ')}}" > Article Management </a>

Let's look at the magic thing, start the built-in test server:

$php App/console Server:run

Well, we've completed this 10-minute blog and all the code is controller/articlecontroller.php,form/articletype.php,resource/views/article/*. In Html.twig, we have completed the most basic article management functions. Of course, after you are familiar with Symfony, you may not need to rely entirely on symfony to help you generate these additions and deletions to check operations, but at least symfony with a command to let everything first run up, this is not the prototype we want?

This article permanent address:
This article comes from IT985 blog, reprint, please indicate the source and corresponding link.

For more information about PHP framework interested readers can view the site topics: "PHP Excellent Development Framework Summary", "CodeIgniter Introductory Course", "CI (CodeIgniter) Framework Advanced Course", "Yii framework Introduction and common skills Summary" and " thinkphp Getting Started Tutorial "

I hope this article will help you with the PHP program design based on Symfony framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.