Symfony Learning 10-minute Introductory classic tutorial, Symfony 10-minute _php tutorial

Source: Internet
Author: User
Tags php framework codeigniter

Symfony Learning 10-minute Introductory classic tutorial, Symfony 10 minutes


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

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

$git Clone Https://github.com/saharabear/symfony-sample.git

Project initialization

First, you need to install the PHP environment on your computer and install Git. This is the content of the basic content, there are a lot of tutorials on the network, there is not much to introduce, but the point is: PHP starting from 5.4, has built-in test server, Symfony also embraced this PHP built-in server, only need to use $php app/console server:run on the command line to start testing the Symfony framework-based PHP program, so it is unnecessary to use a complex integrated environment such as XAMPP, Install PHP directly and make sure you can execute PHP commands at the command line.

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

$CD Symfony-sample$curl-ss Https://getcomposer.org/installer | Php

If you would like more information about composer, you can refer to this website.

After the installation is complete composer, we can start to install the latest version of Symfony2.6.0
Copy the Code code 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 case, we will use the MySQL database, so you can go all the way to press ENTER, do not care about how this configuration should be filled. Anyway, Symfony will be successful after installation, generate a configuration file, called App/config/parameters.yml, below I will provide a sample of parameters.yml files, as long as the copy in it, do not have to pay attention to so many details.

After the Mysampleproject was created, the Mysampleproject directory was generated under the Symfony-sample directory, and I was used to putting the program in the root of the project, so I executed a few commands below. You can move the project from the Symfony-sample/mysampleproject directory to the Symfony-sample directory

$MV mysampleproject/*./$rm-RF Mysampleproject

In theory, we have completed the creation of the Symfony project, but the parameters.yml file just mentioned has not been explained. This parameters.yml is a symfony global configuration file that can be placed in this file, whether it be database configuration information or any other configuration. Here is the test parameters.yml we need to use, remember to change the value of the last line to a random value

# 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

Use this paragraph directly, replace the contents of the App/config/parameters.yml file, then edit the APP/CONFIG/CONFIG.YML, find the following lines, add the last line and save.

Driver:  "%database_driver%" host: "   %database_host%" Port:   "%database_port%" dbname:  "% Database_name% "User:   "%database_user% "Password:"%database_password% "Charset:utf8path:   "%database_ path% "

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

Build Bundles

Let's talk about what bundles are. Symfony is based on Di, maybe you don't know what di is, it doesn't matter, it doesn't matter, you can think of symfony di as a function pool, make all the functions in the program into bundles, or you can interpret bundles as a combination of PHP files. such as user registration, login function made a bundle, you can also put a forum post Huitie function into a bundle, nature can also be a bundle of article management, and then use a bundle to invoke and configure different bundles, Then you can assemble the site, and the various bundles you write can continue to be reused in other applications, so the more bundles you write, the more reusable you will be, and the more favorable it will be to create new projects.

We're going to build our bundles right now. On the command line, use the command:

$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 want to generate the whole directory structure [no]? YESDO you confirm generation [Yes]? Yesgenerating the bundle code:okchecking 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

This successfully established our bundle, called Symfonysamplebundle, we use the bundle namespace is Symfony/bundle/samplebundle, this is a convention, We can also build other bundles, such as symfony/bundle/postbundle, or symfony/bundle/articlebundle, and the corresponding bundles The name is Symfonypostbundle or Symfonyarticlebundle, respectively. You can also build these bundles yourself, which does not affect our current tutorials.

Yes, in the bundle we created, the following directories were generated:

①entity: This directory is not required, and in many cases it is generated only 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 controllers, which is the C in MVC
③resources: This directory also has subdirectories, where views placed the template, that is, MVC in the V, and public place is static files, such as JS, CSS, images and so on
④tests: Code to place unit and integration tests, which is not required in this sample program
⑤dependencyinjection: The directory associated with Di, for the time being, does not need to know
⑥symfonysamplebundle.php: Current definition file for this bundle

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

Design entity

In the MVC design concept, M is the most important, because the content of M expression is the business logic. I think if this place goes deep into the discussion, there will always be a blood-rich model or anemia model, but there is no need to think about this much at this time in this tutorial, you just need to know that the entity is the M in MVC, which is used to express business logic. For example, if we want to develop an article management system, then the article itself represents the business logic. For example, our article to 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 can be empty, these also belong to the business logic. At the same time, this article needs to be stored, such as stored in a database, then this m should be able to map to the database table. We put this m, called the entity.

or talk less nonsense, directly on the code. So how do you build entities? It is not written from scratch 1.1, of course, but it is generated directly from the following command:

$php App/console Generate:doctrine:entityWelcome to the Doctrine2 entity generatorthis command helps you generate doctrine 2 entities. First, you need to give the entity name of your want to generate. You must use the shortcut notation like AcmeBlogBundle:Post.The Entity shortcut name:SymfonySampleBundle:ArticleDetermin E The format to use for the mapping information. Configuration format (yml, XML, PHP, or annotation) [Annotation]:ymlinstead of starting with a blank entity, can add s ome 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, Datet Imetz,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 STO P 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):D O-want to generate an empty repository class [No]? Yessummary before Generationyou is going to generate a "symfonysamplebundle:article" Doctrine2 entityusing the "yml" form At. Do you confirm generation [Yes]? Yesentity generationgenerating The entity Code:okyou can now start using the generated code!

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

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 * * @O  Rm\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-&    Gt;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) {$th    Is->author = $author;  return $this;  }/** * Get author * * @return String */Public Function Getauthor () {return $this->author; }}

You can use the code without changing the line. Then we'll do a few more magical things:
Copy the Code code as follows: $php app/console doctrine:schema:update--force

This operation, has already helped you to build the database and the data table through the article.php, you do not need to operate this process, below we also will transform the article.php, but then only then need to re-execute above this operation, Symfony will help you automatically modify the table structure of your database.

Add constraint

We created the article.php, and since this entity represents the specific business logic, we need to consider a few realistic questions:

1. The user must fill in the title and content
2. The user must fill in the title can not exceed 200 words
3. Users can not fill in 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 \generatedvalue (strategy= "AUTO") */private $id; /** * @var String * @Assert \notblank (message= "title cannot be Empty") * @Assert \length (* max=200, * maxmessage= "title cannot exceed 200  Word "*) * @ORM \column (name=" title ", Type=" string ", length=200) */private $title; /** * @var String * * @Assert \notblank (message= "article content cannot be empty") * @ORM \column (name= "content", type= "text") */privat  e $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) {$th    Is->author = $author;  return $this;  }/** * Get author * * @return String */Public Function Getauthor () {return $this->author; }}

Then perform the operation of synchronizing the database:

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

Change and delete

OK, let's do a change to the article and delete the operation. First, execute the following command:

$ php app/console Generate:doctrine:crud Welcome to the Doctrine2 crud generatorthis command helps you generate CRUD Contr Ollers and templates. First, you need to give the entity for which your want to generate a CRUD. You can give a entity that does not exist yet and the wizard would helpyou defining it. You must use the shortcut notation like AcmeBlogBundle:Post.The Entity shortcut Name:SymfonySampleBundle:ArticleBy defaul T, the generator creates, actions:list and show. 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 would be " Mounted "under Thisprefix:/prefix/,/prefix/new, ...). Routes prefix [/article]:/article Summary before generationyou is going to generate a CRUD controller for "Symfonysample Bundle:article "Using 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!

Then, edit the Indexaction in defaultcontroller.php as follows:

/** * @Route ("/", name= "Welcome") * @Template () */public function indexaction () {  return array ()}

Edit the Resource/views/default/index.html.twig content as follows:

Article Management

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

$php App/console Server:run

Well, we've finished 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 the symfony, may not need to rely entirely on symfony help you to generate these additions and deletions to the operation, but at least symfony with a command to let everything run first, this is not the prototype we want it?

Permanent address of this article:http://blog.it985.com/5133.html
This article is from IT985 blog, please indicate the source and corresponding link when reproduced.

Read more about PHP framework related content Readers can view this site: "PHP Excellent Development Framework Summary", "CodeIgniter Introductory Tutorial", "CI (codeigniter) Framework Advanced Tutorial", "Yii framework Introduction and common skills Summary" and " thinkphp Getting Started Tutorial "

It is hoped that this article is helpful to the PHP program design based on Symfony framework.

Articles you may be interested in:

    • High performance PHP Framework Symfony2 Classic Introductory Tutorial
    • PHP's Symfony and CodeIgniter framework's nginx rewrite rule configuration
    • An example analysis of Symfony data verification method
    • Symfony form and page implementation tips
    • Symfony A basic example of creating a page
    • How to export data to a CSV file in Symfony
    • Symfony2 Session Usage Example analysis

http://www.bkjia.com/PHPjc/1098686.html www.bkjia.com true http://www.bkjia.com/PHPjc/1098686.html techarticle Symfony Learning 10-minute Introductory classic tutorial, Symfony 10 minutes Symfony is a powerful PHP-based Web development framework, where we use 10 minutes to do a simple delete and change ...

  • 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: info-contact@alibabacloud.com 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.