In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces how to use Symfony, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Symfony is a powerful PHP-based Web development framework, here we spend ten minutes to do a simple add, delete, modify and check the program, anyone who is not familiar with Symfony can complete their first Symfony program through this tutorial.
If you need the full source code of the sample program, you can visit it here or get the source code by:
$git clone https://github.com/saharabear/symfony-sample.git
Project initialization
First of all, you need to install the PHP environment and install git on your computer. This aspect belongs to the basic content, there are a large number of tutorials on the network, which will not be introduced here, but one point to remind you is: PHP has built-in testing server since 5.4.The Symfony has embraced this server built-in by PHP. You only need to use $php app/console server:run on the command line to start a PHP program based on the Symfony framework for testing. Therefore, it is not necessary to use a complex integrated environment like XAMPP, just install PHP and make sure that php commands can be executed from the command line.
Then, we need to create a new directory called symfony-sample,Symfony and use 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, 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 begin to install the latest version of Symfony2.6.0
$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 enter all the way, do not worry about how all this configuration should be filled in. Anyway, Symfony will generate a configuration file called app/config/parameters.yml after the installation is successful. I will provide a sample of the contents of the parameters.yml file below, as long as you copy it, you don't have to pay attention to so many details.
After I just created mysampleproject, I generated the mysampleproject directory in the symfony-sample directory. I'm used to putting the program in the root directory of the project, so by executing the following commands, I 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 the global configuration file for Symfony, and can be placed in this file, whether it is database configuration information or various other configurations. 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
Just use this paragraph, replace the contents of 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: UTF8path: "% database_path%"
OK, so we have completed the configuration of the basic Symfony program, and you now have a basic program prototype configured with the database, mail sender, and logging system. Next, let's start writing our own Symfony program.
Establish Bundle
Let's first talk about what Bundle is. Symfony is based on DI, maybe you don't know what DI is, it doesn't matter, it doesn't matter, you can understand the DI of Symfony as a function pool, make all the functions in the program into Bundle, or you can understand Bundle as a combination of php files. For example, if users register and log in to make a Bundle, you can also turn the post and reply function of a forum into a Bundle, and naturally you can also make the article management into a Bundle, and then use a Bundle to call and configure different Bundle. Then you can assemble the website, and the various Bundle you write can continue to be reused in other applications. The more Bundle you write, the stronger the reusability. The more advantageous it is to make new projects.
Let's build our own Bundle 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 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
In this way, we successfully set up our Bundle, whose name is SymfonySampleBundle, and the Bundle namespace we use is Symfony/Bundle/SampleBundle, which is a convention, and we can also build other Bundle, such as Symfony/Bundle/PostBundle, or Symfony/Bundle/ArticleBundle, and the corresponding Bundle name is SymfonyPostBundle or SymfonyArticleBundle. You can also create these Bundle yourself, which will not affect our current tutorials.
By the way, in the Bundle we created, the following directories will be generated:
① Entity: this directory is not required. In many cases, the model is generated and placed only when the entity is generated, that is, the M in MVC.
② Controller: this directory generates DefaultController.php, where you can set up your own Controller controller, that is, C in MVC
③ Resources: there are also subdirectories under this directory, where views places templates, that is, V in MVC, and public places static files, such as js, css, images, and so on.
④ Tests: code for placing unit tests and integration tests, not needed for the time being in this sample program
⑤ DependencyInjection: directories related to DI, which you don't need to know for the time being
⑥ SymfonySampleBundle.php: the definition file for the current Bundle
You can read the Symfony official documentation for more details, and the current focus is to get the Symfony sample program up and running.
Design entity
In the design philosophy of MVC, M is the most important, because the content that M expresses is business logic. I think if you go further into this place, you will go all the way to the blood-rich model or the anemia model, but you don't need to think about it so much in this tutorial right now, 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 should have a title, content, and author, then these three items belong to business logic, while the title cannot be empty, the length cannot exceed 200, the content cannot be empty, but the author can be empty, these also belong to business logic. At the same time, this article needs to be stored, such as in a database, so that the M should be able to map to a table in the database. Let's call this M an entity.
Let's cut the crap and go straight to the code. So how to build an entity? Of course, instead of writing bit by bit from the beginning, it is generated directly with the following command:
$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!
After these commands, you will find that a new file, Article.php, has been 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 * * @ 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;}}
You can use this code line by line. At this time, let's do a few more magical operations:
The copy code is as follows:
$php app/console doctrine:schema:update-force
This operation has helped you to set up the database and data table through Article.php, you do not need to operate this process yourself, below we will also modify the Article.php, and then only need to re-execute the above operation, Symfony will help you automatically modify the table structure of the database.
Add constraint
We created Article.php above, and since this entity represents specific business logic, we need to consider several practical issues:
1. Users must fill in the title and content
two。 The title filled in by the user cannot exceed 200 words.
3. Users can not fill in the author.
These belong to the business logic, and we can modify the 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 words" *) * @ 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") * / 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 operation of synchronizing the database:
$php app/console doctrine:schema:update-- forceUpdating database schema...Database schema updated successfully! "1" queries were executed
Add, delete, modify and check
All right, let's do an addition, deletion, modification and search operation for the article. First, execute the following command:
$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: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 as follows:
Article management
Let's look at the amazing thing and start the built-in test server:
Php app/console server:run thank you for reading this article carefully. I hope the article "how to use Symfony" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.