symfony 2_使用Symfony 2:构建Web应用程序

symfony 2

介绍 (Introduction)

The Symfony PHP Framework is powerful, scalable and flexible. Yet it is considered by many, especially those new to frameworks, to have a very steep learning curve.

Symfony PHP框架功能强大,可扩展且灵活。 然而,许多人(尤其是那些刚接触框架的人)认为它的学习曲线非常陡峭。

This is true to a certain extent. At first glance, Models, Views, Controllers, Entities, Repositories, Routing, Templating, etc, altogether can appear very terrifying and confusing.

在一定程度上是正确的。 乍一看,模型,视图,控制器,实体,存储库,路由,模板等,总会显得非常恐怖和混乱。

However, if you have grasped the fundamentals of PHP and HTML, have a basic understanding of modern web site development (in particular, Pretty URIs, MVC), and know how to CRUD a database/table, you are not far from developing a fairly good website, be it for your personal usage or business application.

但是,如果您掌握了PHP和HTML的基础知识,对现代网站开发有基本的了解(尤其是Pretty URI,MVC),并且知道如何对数据库/表进行CRUD,那么您就可以轻松地开发出相当不错的数据库/表了。好的网站,无论是供您个人使用还是用于商业应用。

In this series, I will capture a few key steps and some advanced techniques (image manipulation, pagination, dynamic contents, NativeQuery, etc) to help anyone who is considering using Symfony (note, to avoid future confusion, Symfony here refers to the Symfony 2, not the obsolete Symfony 1) as their PHP framework to develop a website.

在本系列中,我将捕获一些关键步骤和一些高级技术(图像处理,分页,动态内容,NativeQuery等),以帮助正在考虑使用Symfony的任何人(请注意,为避免将来造成混淆,此处的Symfony指的是Symfony)。 2,不要过时的Symfony 1)作为自己PHP框架来开发一个网站。

I will use my personal book collection site as the starting point. It is up and running, so the project I use here is not a demo but a real running site (hosted at http://www.rsywx.net, in pure Chinese).

我将以我的个人藏书网站为起点。 它已经启动并正在运行,因此我在这里使用的项目不是演示而是一个实际的运行站点(以纯中文托管在http://www.rsywx.net上 )。

The final source code of the site for this part of the tutorial can be found at the Github repository. Any comments and queries, please feel free to contact me.

该教程本部分的最终站点源代码可以在Github存储库中找到。 任何意见和疑问,请随时与我联系

快速设置 (Quick setup)

Setting up Symfony is fairly easy. My favorite way is to download the Symfony Standard without vendors package. Visit the official download site and make sure you choose the right package. Unzip/Untar the archives to your planned web root directory and you are almost there (my project for this series will be located at f:\www\rsywx_test). After unzipping the Symfony package, you will see a directory structure not unlike this one:

设置Symfony非常容易。 我最喜欢的方法是下载没有供应商软件包的Symfony Standard。 访问官方下载站点 ,并确保您选择正确的软件包。 将归档文件解压缩/解压缩到计划的Web根目录,您就快到了(本系列的我的项目将位于f:\ www \ rsywx_test)。 解压缩Symfony程序包后,您将看到一个与以下结构相同的目录结构:

alt

Be sure the above directory is correct (you may not see the .hg directory as this is for version control only).

确保以上目录正确(您可能看不到.hg目录,因为该目录仅用于版本控制)。

The next step is to download the PHP packaging system called Composer. Most modern PHP frameworks use Composer for package management.

下一步是下载名为ComposerPHP打包系统。 大多数现代PHP框架都使用Composer进行程序包管理。

If you have the cURL utility installed, you can issue the following command:

如果安装了cURL实用程序,则可以发出以下命令:

curl -S https://getcomposer.org/installer | php

or if not (but you really should install cURL), punch in the following:

否则(如果您确实应该安装cURL),则输入以下内容:

php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

There will be one new file downloaded, called composer.phar. This file is the entry point for our PHP package management.

将下载一个名为composer.phar的新文件。 该文件是我们PHP软件包管理的入口点。

As the name of the archive suggests, the files we have now contain no libraries (or bundles) to make Symfony really work. To do that, you need to run:

就像档案名称所暗示的那样,我们现在没有包含使Symfony真正起作用的库(或捆绑包)的文件。 为此,您需要运行:

php composer.phar update

The above will install the latest and necessary bundles normally required. If you run into any errors (missing utilities, critical dependencies that cannot be met..) composer will kindly let you know. The installation procedure should be done within a couple minutes at most, depending on your connection speed.

上面将安装通常需要的最新和必要的软件包。 如果您遇到任何错误(缺少实用程序,无法满足的重要依赖关系..),作曲家将通知您。 安装过程最多应在几分钟之内完成,具体取决于您的连接速度。

If you have setup your web server (I am using Apache) correctly, you can visit the site already:

如果您已经正确设置了Web服务器(我正在使用Apache),则可以访问该网站:

alt

With Symfony, it is common practice to use app_dev.php as the entry page during development. In a production environment, app_dev.php would be omitted.

使用Symfony,通常的做法是在开发过程app_dev.php用作入口页面。 在生产环境中, app_dev.php将被省略。

Feel free to navigate around to get a feeling of the framework and familiarize yourself with the toolbars and debug messages it offers.

随意浏览以了解框架,并熟悉工具栏并调试其提供的消息。

Detailed setup instructions can be found here, in case you need more help.

如果您需要更多帮助,可在此处找到详细的设置说明。

It is always a good idea to run php composer.phar selfupdate periodically to get the latest composer.phar distribution.

定期运行php composer.phar selfupdate以获得最新的composer.phar发行版总是一个好主意。

Note: The Symfony package always has a built-in bundle called AcmeDemoBundle. That bundle is a demo app that proves Symfony is up and running, and serves as an example which you can use to build your own app. To remove that bundle out of your web site setup, please follow the instructions in this article.

注意: Symfony软件包始终具有一个称为AcmeDemoBundle的内置捆绑软件。 该捆绑软件是一个演示应用程序,可证明Symfony已启动并正在运行,并作为示例,您可以用来构建自己的应用程序。 要从您的网站设置中删除该捆绑软件,请按照本文中的说明进行操作。

After removing, if you visit the site again, you will see a 404 page (No route found for "GET /") as we have not started to create our own application yet.

删除后,如果您再次访问该站点,您将看到一个404页(找不到“ GET /”的路由),因为我们尚未开始创建自己的应用程序。

捆绑,控制器,视图,模型(实体) (Bundle, Controllers, Views, Models (Entities))

In short, Symfony relies on bundles (often called modules in other frameworks). A bundle can be treated as a collection of files – it serves as the container for data retrieving, logic control and presentation of a particular function set or sets in your website. My site has only one bundle and serves to list all of my books, the detail of one book, the articles I wrote after reading a book, my favorite NBA team (Lakers) scores, etc. These functions (or modules as they're counterintuitively called in Symfony) are all encapsulated in one bundle (trrsywxBundle).

简而言之,Symfony依赖于捆绑软件(在其他框架中通常称为模块)。 捆绑包可被视为文件的集合–它充当用于数据检索,逻辑控制以及网站中一个或多个特定功能集的呈现的容器。 我的网站只有一个捆绑软件,可列出我的所有书籍,一本书的详细信息,我读完一本书后写的文章,我最喜欢的NBA球队(湖人)得分等。这些功能(或以下模块)违反直觉的在Symfony中称为)都封装在一个包中(trrsywxBundle)。

A bundle will contain controllers, views and entity files (models). These constitute the foundation of an MVC-structured website.

捆绑包将包含控制器,视图和实体文件(模型)。 这些构成了MVC结构的网站的基础。

To generate a bundle and start our application development, issue the below command:

要生成捆绑包并开始我们的应用程序开发,请发出以下命令:

php app/console generate:bundle

Before creating the bundle, the console will ask you several questions:

在创建捆绑软件之前,控制台将询问您几个问题:

  • Bundle namespace: in this example, I am using tr\rsywxBundle. Be sure to have "Bundle" at the end.

    捆绑名称空间:在此示例中,我使用的是tr \ rsywxBundle。 确保最后有“捆绑包”。
  • Bundle name: use the suggested name derived from the namespace. In this case, "trrsywxBundle".

    捆绑包名称:使用从名称空间派生的建议名称。 在这种情况下,为“ trrsywxBundle”。
  • Target Directory: use the suggested lcoation ("F:/www/rsywx_test/src" in this case).

    目标目录:使用建议的名称(在这种情况下为“ F:/ www / rsywx_test / src”)。
  • Configuration format: there are 4 options available: PHP, YAML, XML and annotation. Choose the one your prefer and feel comfortable with. If you'd like to follow along, I will use YAML, so type "yml" as your choice.

    配置格式:有4个可用选项:PHP,YAML,XML和注释。 选择您喜欢的一种并且感觉舒适。 如果您想继续,我将使用YAML,因此请输入“ yml”作为您的选择。
  • Do you want to generate the whole directory structure: Not necessary.

    是否要生成整个目录结构:不需要。
  • Confirm the generation, kernel update and Routing generation.

    确认生成,内核更新和路由生成。

More detailed instructions about this process can be found here.

有关此过程的更多详细说明,请参见此处

路由 (Routing)

Consider routing as a mapping mechanism from the HTTP request to the module/function that really handles it (processing the request, grabbing data, and rendering the proper response back to the web browser).

考虑将路由作为从HTTP请求到真正处理它的模块/功能(处理请求,获取数据并将适当的响应呈现回Web浏览器)的映射机制。

Like most other frameworks, Symfony has a routing feature to support pretty URIs. This is done by creating routes in routing.yml (and by having the right .htaccess configuration, which is located in the web/ directory of your Symfony setup).

与大多数其他框架一样,Symfony具有路由功能以支持漂亮的URI 。 这是通过在routing.yml中创建路由来完成的(并具有正确的.htaccess配置,该配置位于Symfony设置的web /目录中)。

To make the encapsulation stronger, I do recommend you add your own routes in the bundle's routing.yml file (located under path-to-your-site-root/src/tr/rsywxBundle/Resources/config). This comes in handy when you eventually want to port the whole bundle into another site. Please note how the namespace of the bundle is reflected in the directory structure.

为了使封装更牢固,我建议您在捆绑包的routing.yml文件(位于您的站点根目录 / src / tr / rsywxBundle / Resources / config下)中添加自己的路由。 当您最终希望将整个捆绑包移植到另一个站点时,这很方便。 请注意捆绑的名称空间如何反映在目录结构中。

A common pitfall when defining routes is that routes have their precedence. The earlier a route appears, the earlier it will be matched. In other words, if the routes are not arranged properly, weird, difficult to debug problems will occur.

定义路由时常见的陷阱是路由具有优先级。 路线越早出现,将越早被匹配。 换句话说,如果路由安排不正确,怪异,难以调试,则会出现问题。

For example, in an earlier version of my site, I had two routes looking like this:

例如,在我的网站的早期版本中,我有两条看起来像这样的路线:

tag_list:
  pattern: /books/{tag}/{page}
  defaults: {_controller: trrsywxBundle:Book:taglist, page:1}   
...  
reading_list:
  pattern: /books/readings/{page}
  defaults: {_controller: trrsywxBundle:Reading:list, page:1}

See the problem? /books/readings will actually be mapped to tag_list route, in which the parameter tag will take readings as its value and directs us to a totally different controller. I can't simply switch the order of these two routes (which would solve most of the issues, but crash when someone is really looking for books containing 'readings' as a tag). The only way to get around this is to change the route pattern for the first one:

看到问题了吗? /books/readings实际上将映射到tag_list路由,在该路由中,参数tag会将readings作为其值,并将我们定向到一个完全不同的控制器。 我不能简单地切换这两条路线的顺序(这可以解决大多数问题,但是当有人真正在寻找包含“读数”作为标签的书时会崩溃)。 解决此问题的唯一方法是更改​​第一个的路线模式:

tag_list:
  pattern: /books/tag/{page}/{tag}
  defaults: {_controller: trrsywxBundle:Book:taglist, page:1}

Derived from the fact that the earlier a route appears, the earlier it is matched, you need to put the most frequently used routes at the beginning of the routing.yml file. This has the added benefit of being faster, since the framework has fewer routes to check before hitting a match.

由于路由出现的越早,匹配的越早的事实,您需要将最常用的路由放在routing.yml文件的开头。 由于框架在命中之前要检查的路线较少,因此具有更快的优势。

I am not covering the whole aspect of routing in Symfony here. The official documentation says it all.

我不会在这里介绍Symfony中路由的整个方面。 官方文档说明了一切。

数据库 (Database)

In this project, the database used is relatively simple. A few tables are created to reflect the book information (title, author, publisher, purchase date, location, etc), my reading thoughts, the Lakers score, Quote Of The Day, etc. Most of the tables (books, readings, publisher, purchase place, etc) are related to each other with a One-To-Many relationship. The tags table and books table are linked with Many-To-Many relationships.

在此项目中,使用的数据库相对简单。 创建了一些表格来反映图书信息(书名,作者,出版商,购买日期,位置等),我的阅读思想,湖人得分,《今日行情》等。大多数表格(书籍,图书,出版商) ,购买地点等)之间存在一对多关系。 标签表和书本表与多对多关系链接。

The rsywx.sql file in the project's misc folder will let you import the database (MariaDB or MySQL) – simply import it via the mysql command line tool, or through a web GUI like PhpMyAdmin. Though Symfony official documentation suggests databases/tables be created from within the Symfony framework, I strongly suggest using another 3rd party tool. The advantages of using a 3rd party tool include:

该项目的misc文件夹中的rsywx.sql文件将允许您导入数据库(MariaDB或MySQL)-只需通过mysql命令行工具或通过Web界面(如PhpMyAdmin)进行导入。 尽管Symfony官方文档建议在Symfony框架内创建数据库/表,但我强烈建议使用其他第三方工具。 使用第三方工具的优势包括:

  • More intuitive and straightforward definition of the database;

    更直观,直接的数据库定义;
  • Less typings when defining the data type, relationships, indexes, primary keys, etc.

    定义数据类型,关系,索引,主键等时,键入较少。

We can now link up the database by configuring app/config/parameters.yml:

现在,我们可以通过配置app/config/parameters.yml来链接数据库:

parameters:
  database_driver: pdo_mysql
  database_host: 127.0.0.1
  database_port: null
  database_name: symfony
  database_user: root
  database_password: null

Normally, you will only change the dabase name, user and password to reflect your own choices.

通常,您只会更改数据库名称,用户名和密码以反映您自己的选择。

After creating the database/tables, it is easy to import these database structures into Symfony:

创建数据库/表之后,很容易将这些数据库结构导入Symfony:

php app\console doctrine:mapping:import

And then create the corresponding entities by:

然后通过以下方式创建相应的实体:

php app\console doctrines:generate:entity tr

(where tr is the namespace of the bundle).

(其中tr是捆绑软件的名称空间)。

Note: Symfony supports two ORMs for now: Doctrine and Propel. I am using Doctrine in this application.

注意: Symfony现在支持两个ORM:Doctrine和Propel。 我在此应用程序中使用Doctrine。

In general, the import will succeed with next to no problems. However, there are at least two things to notice:

通常,导入将成功,几乎没有问题。 但是,至少要注意两点:

  • The tool is not good at mapping a table with a compound primary key (i.e., a primary key with 2 or more fields) in which at the same time, one of the fields is also a foreign key to another table

    该工具不适合将具有复合主键(即,具有2个或多个字段的主键)映射到表,而其中的一个字段同时也是另一个表的外键
  • You can edit the generated entity files (located under path-to-your-site-root/src/tr/rsywxBundle/Entity/). But if you modified the field names, types and other information, be sure to "reflect" those changes back to the database via the php app/console doctrine:database:create command. Don't worry, Syfmony is stronger and smarter now. The command will not destroy the data you loaded before.

    您可以编辑生成的实体文件(位于您的站点根目录 / src / tr / rsywxBundle / Entity /下)。 但是,如果您修改了字段名称,类型和其他信息,请确保通过php app/console doctrine:database:create命令将这些更改“反映”回数据库。 别担心,Syfmony现在更强大,更智能。 该命令不会破坏您之前加载的数据。

结论 (Conclusion)

In this part of the tutorial, we set the project and the Symfony framework up, put the database in place and did a clean-up job (removing the built-in AcmeDemoBundle).

在本教程的这一部分中,我们将设置项目和Symfony框架,将数据库放置到位并进行清理工作(删除内置的AcmeDemoBundle)。

Having the framework ready for proper further development is often the most difficult part of starting a project, especially when dealing with a framework you've never dealt with before. So far, I hope the setup is still easy and straightforward enough. Symfony is the most well-documented framework that I have ever come across, so if you still have problems be sure to visit the Official Documentation and The Cookbook for help, or just get in touch. Again, the final code of this part of the tutorial is available on Github.

准备好框架以进行适当的进一步开发通常是启动项目中最困难的部分,尤其是在处理您从未处理过的框架时。 到目前为止,我希望安装过程仍然足够简单和直接。 Symfony是我见过的记录最完整的框架,因此,如果您仍然有问题,请确保访问“ 官方文档”“食谱”以寻求帮助,或者只是保持联系。 同样,本部分最后的代码可以在Github上找到

Next time, we'll create routes, controllers (to guide the application flow and logic), entities/repositories (to retrieve data), and templates (for presentation) to make the site functional.

下次,我们将创建路由,控制器(以指导应用程序流程和逻辑),实体/存储库(以检索数据)和模板(用于演示)以使站点正常运行。

翻译自: https://www.sitepoint.com/building-a-web-app-with-symfony-2-bootstrapping/

symfony 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值