symfony2_使用Symfony 2构建Web应用程序:一次单击即可满足您的需求

symfony2

Symfony 2 tutorial. Mobile application has taken a huge leap. Today, mobile applications are not just apps anymore – they are actually solutions to business issues. From a simple informative app to a critical business application, mobile apps have become a powerful tool that efficiently supports marketing strategies of a business.

Symfony 2教程。 移动应用程序取得了巨大飞跃。 如今,移动应用程序不再仅仅是应用程序,它们实际上是业务问题的解决方案。 从简单的信息应用程序到关键的业务应用程序,移动应用程序已成为功能强大的工具,可以有效地支持企业的营销策略。

Just open your phone and everything is available in your hands in the form of web apps starting from very basic daily essentials to luxuries and entertainment like music, gaming, banking, shopping, ticketing, billing recharges and so on. Now the real question is how to build a web app. Thanks to the availability of a wide range of developers who share their experiences and knowledge online, you can easily find the relevant information and documentation on building an app. Similarly like you search ‘how to create a blog’ and get thousands of solutions, you can search “building a web app using symphony” to get the most relevant answer.

只需打开电话,Web应用程序就可以提供一切功能,从最基本的日常必需品到奢侈品和娱乐活动,例如音乐,游戏,银行业务,购物,票务,计费充值等。 现在真正的问题是如何构建Web应用程序。 由于有众多在线开发人员共享经验和知识,因此您可以轻松找到有关构建应用程序的相关信息和文档。 同样,就像您搜索“如何创建博客”并获得数千种解决方案一样,您可以搜索“使用Symphony构建Web应用程序”以获得最相关的答案。

However, before you get started, make sure your web app is:

但是,在开始之前,请确保您的Web应用程序是:

  • User friendly

    方便使用的
  • technically concrete

    技术上具体
  • easily accessible

    容易获得
  • Less time consuming

    耗时少
  • Less viable to unauthorized access

    对未经授权的访问不太可行
  • On the toplist of various search engines like Google, yahoo, playstore etc.

    在各种搜索引擎(例如Google,yahoo,playstore等)的榜首。

Building a web app is quite a technical process but having a little knowledge of basic languages and learning a basic web development program, you can easily create a web application for your personal use.

构建Web应用程序是一个技术过程,但是对基本语言有所了解并学习了基本的Web开发程序,因此您可以轻松创建供个人使用的Web应用程序。

In the following series, I will discuss some techniques and key steps that may help you build your own website using Symfony. It is a three-layered process which involves:

在以下系列中,我将讨论一些技术和关键步骤,这些技术和关键步骤可以帮助您使用Symfony构建自己的网站。 这是一个三层过程,涉及:

Bootstrapping or Rebooting: The very first step is to download the Symfony standard from its official site followed by unzipping the archives to the web root directory.

引导或重新引导:第一步是从其官方站点下载Symfony标准,然后将归档文件解压缩到Web根目录。

After this you need to download the PHP packaging system which is known as composer. Now there can be two possibilities:

之后,您需要下载被称为作曲家PHP打包系统。 现在可以有两种可能性:

1. If you already have the cURL utility installed, issue the following command: curl -S https://getcomposer.org/installer | php

1.如果已经安装了cURL实用程序,请发出以下命令: curl -S https://getcomposer.org/installer | php curl -S https://getcomposer.org/installer | php

2. Else issue the below command: php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

2.否则发出以下命令: php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

You will get a new downloaded file known as composer.phar. This file is the entry point for our PHP package management. The files that we have known contain no bundles so as to make Symfony work. For that you need to run: phpcomposer.phar update

您将获得一个新的下载文件,称为composer.phar。 该文件是我们PHP软件包管理的入口。 为了使Symfony正常工作,我们已知的文件不包含捆绑软件。 为此,您需要运行: phpcomposer.phar update

This will install all the required bundles and in case you run into errors i.e. missing utilities or critical dependencies, composer will let you know about that. Depending upon the speed of your connection the aforesaid installation procedure will complete itself within the couple of minutes.

这将安装所有必需的捆绑软件,并且如果您遇到错误(例如,缺少实用程序或重要依赖项),composer将让您知道。 根据您的连接速度,上述安装过程将在几分钟内完成。

With Symfony, the common practice is to use app_dev.php as the initial page during development, on the other hand when it comes to production app_dev.php would be omitted.

使用Symfony,通常的做法是在开发过程中将app_dev.php用作初始页面,另一方面,在生产中将省略app_dev.php。

With the resources provided by Symfony one can feel free to search and familiarize themselves with the framework, toolbars and the debug messages without any obstruction.

借助Symfony提供的资源,您可以自由搜索并熟悉框架,工具栏和调试消息,而不会受到任何阻碍。

To get the latest composer.phar framework, you must periodically run composer.phar self-update

要获取最新的composer.phar框架,必须定期运行composer.phar self-update

There is one more feature provided on Symfony webpage i.e. it has a demo app in the form of a bundle known as AcmeDemoBundle which can be used as an example to build your own app.

Symfony网页上提供了另一项功能,即以捆绑形式的演示应用程序称为AcmeDemoBundle,可以用作构建自己的应用程序的示例。

模块(实体) (Modules (Entities))

In Symfony, modules are also referred to as Bundle, Controllers, Views, and Models. A controller is a collection of files which serves as the canister for logic control, data retrieving and presentation of a particular set of function in your website.

在Symfony中,模块也称为捆绑,控制器,视图和模型。 控制器是文件的集合,用作逻辑控制,数据检索以及网站中特定功能集的展示的容器。

Bundle or controller or entity serves as the foundation of an MVC-structured website.To initiate the application development and generate a bundle, run the following command:

捆绑包,控制器或实体是MVC结构网站的基础。要启动应用程序开发并生成捆绑包,请运行以下命令:

php app/console generate:bundle

php app/console generate:bundle

The console will ask you various questions before creating a bundle such as:

在创建捆绑包之前,控制台将询问您各种问题,例如:

  • Bundle namespace: Be sure to have "Bundle" at the end.

    捆绑名称空间:确保最后有“捆绑”名称。
  • Bundle name: use the suggested name derived from the namespace.

    捆绑包名称:使用从名称空间派生的建议名称。
  • Target Directory

    目标目录
  • Configuration format: You are available with 4 options i.e. PHP, YAML, XML and annotation. You can opt for any one.

    配置格式:您可以使用4个选项,即PHP,YAML,XML和注释。 您可以选择任何一个。
  • Would you like to generate the whole directory structure: Not necessary.

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

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

Routing is nothing but a mapping mechanism which processes the request, grabs the data and render the response to the web browser. You can download all the routes via app/config/routing.yml You have the provision for defining your own route. You can create your route in MyBundle/Resouces/config and then import the same in app/config/routing.yml:

路由不过是一种映射机制,用于处理请求,获取数据并将响应呈现给Web浏览器。 您可以通过app/config/routing.yml下载所有路线。您可以定义自己的路线。 您可以在MyBundle/Resouces/config创建您的路由,然后在app/config/routing.yml中将其导入:


Acme_hello:
	Resource: "@AcmeHelloBundle/Resouces/config/routing.yml"

Acme_hello:
	Resource: "@AcmeHelloBundle/Resouces/config/routing.yml"

数据库 (Database)

Configuring the database with Symfony 2 is relatively simpler and can be done by issuing the following command app/config/parameters.yml:

使用Symfony 2配置数据库相对来说比较简单,可以通过发出以下命令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

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

Parameters that can be customized in a database are: – database name – user – password

可以在数据库中自定义的参数为:–数据库名称–用户–密码

Once the database is created, same can be imported into Symfony:

创建数据库后,可以将其导入到Symfony中:

php app\console doctrine:mapping:import

php app\console doctrine:mapping:import

Followed by the creation of corresponding entities by:

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

php app\console doctrines:generate:entitytr

php app\console doctrines:generate:entitytr

(Or wherever is the namespace of the bundle). Symfony usually supports two ORMs: Doctrine and Propel. You can go for any one of the ORM.

(或捆绑软件的名称空间在哪里)。 Symfony通常支持两种ORM:Doctrine和Propel。 您可以去任何一个ORM。

发展: (DEVELOPMENT:)

We are ready with the framework set up and database. Next step is to make it functional by creation of routes, controllers, repositories and templates.

我们已经准备好框架设置和数据库。 下一步是通过创建路由,控制器,存储库和模板来使其起作用。

路线 (Routes)

Format used by Symfony in order to configure the routes for various applications is YAML Format. One of the examples illustrating the same is mentioned below: File location: src/tr/rsywxBundle/Resources/config/routing.yml

Symfony用于配置各种应用程序路由的格式为YAML格式。 下面提到了说明该问题的示例之一:文件位置: src/tr/rsywxBundle/Resources/config/routing.yml


home:
pattern:  /
defaults: { _controller: trrsywxBundle:Default:index }
contact:
pattern: /contact
defaults:
        _controller: FrameworkBundle:Template:template
template: 'trrsywxBundle:Default:contact.html.twig'
book_list:
pattern: /books/list/{page}/{key}
defaults:
page: 1
key: null
        _controller: trrsywxBundle:Book:list
books_search:
pattern: /books/search
defaults: {_controller: trrsywxBundle:Book:search}
requirements:
        _method: POST
book_detail:
pattern: /books/{id}.html
defaults: { _controller: trrsywxBundle:Book:detail}

home:
pattern:  /
defaults: { _controller: trrsywxBundle:Default:index }
contact:
pattern: /contact
defaults:
        _controller: FrameworkBundle:Template:template
template: 'trrsywxBundle:Default:contact.html.twig'
book_list:
pattern: /books/list/{page}/{key}
defaults:
page: 1
key: null
        _controller: trrsywxBundle:Book:list
books_search:
pattern: /books/search
defaults: {_controller: trrsywxBundle:Book:search}
requirements:
        _method: POST
book_detail:
pattern: /books/{id}.html
defaults: { _controller: trrsywxBundle:Book:detail}

Very first requirement of an app is its entry point which is the "home" route. Pattern defines the URI pattern which the route should match. At an entry point, / is used. defaults:_controller states the action of the application when the route is matched.

应用程序的首要要求是其进入点,即“归属”路线。 模式定义路由应匹配的URI模式。 在入口点,使用/。 defaults:_controller指出匹配路由时应用程序的操作。

控制器 (Controllers)

After routes come Controllers. There are a total of 4 controllers named BookController.php, DefaultController.php, LakersController.php, and ReadingController.php located in src/tr/rsywxBundle/Controller. Two controllers are illustrated below matching book_list and books_search.

路由到达控制器之后。 在src/tr/rsywxBundle/Controller总共有四个名为BookController.php, DefaultController.php, LakersController.php, and ReadingController.php src/tr/rsywxBundle/Controller 。 下面显示了两个匹配book_list和books_search的控制器。


<?php
classBookController extends Controller {
  // ... Many other functions here, see source
  public function listAction($page, $key) {
    $em = $this->getDoctrine()->getManager(); // Get the Entity Manager
    $rpp = $this->container->getParameter('books_per_page'); // Get the global parameter for how many books to show on one page
    $repo = $em->getRepository('trrsywxBundle:BookBook'); // Get the repository
    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key); // Get the result
    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp); // Init the paginator
    $pagelist = $paginator->getPagesList(); // Get the pagelist used for navigation
    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key'=>$key)); // Render the template using necessary parameters
  }
  public function searchAction(Request $req) {
    $q = $req->request->all(); // Get the posted data
    $page = 1; // Get which page to display
    $key = $q['key']; // Get the search criteria
    $em = $this->getDoctrine()->getManager();
    $rpp = $this->container->getParameter('books_per_page');
    $repo = $em->getRepository('trrsywxBundle:BookBook');
    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key);
    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp);
    $pagelist = $paginator->getPagesList();
    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key' => $key));
  }
}

<?php
classBookController extends Controller {
  // ... Many other functions here, see source
  public function listAction($page, $key) {
    $em = $this->getDoctrine()->getManager(); // Get the Entity Manager
    $rpp = $this->container->getParameter('books_per_page'); // Get the global parameter for how many books to show on one page
    $repo = $em->getRepository('trrsywxBundle:BookBook'); // Get the repository
    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key); // Get the result
    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp); // Init the paginator
    $pagelist = $paginator->getPagesList(); // Get the pagelist used for navigation
    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key'=>$key)); // Render the template using necessary parameters
  }
  public function searchAction(Request $req) {
    $q = $req->request->all(); // Get the posted data
    $page = 1; // Get which page to display
    $key = $q['key']; // Get the search criteria
    $em = $this->getDoctrine()->getManager();
    $rpp = $this->container->getParameter('books_per_page');
    $repo = $em->getRepository('trrsywxBundle:BookBook');
    list($res, $totalcount) = $repo->getResultAndCount($page, $rpp, $key);
    $paginator = new \tr\rsywxBundle\Utility\Paginator($page, $totalcount, $rpp);
    $pagelist = $paginator->getPagesList();
    return $this->render('trrsywxBundle:Books:List.html.twig', array('res' => $res, 'paginator' => $pagelist, 'cur' => $page, 'total' => $paginator->getTotalPages(), 'key' => $key));
  }
}

Typically a controller will input parameters, get the entity manager and display the results after necessary processing.

通常,控制器将输入参数,获取实体管理器并在进行必要的处理后显示结果。

实体和存储库 (Entities and Repositories)

Entities are the reflection of database in which we should use straightforward commands to CRUD the data. Repositories are nothing but a customized way to manipulate data.

实体反映了数据库,我们应该在其中使用简单的命令对数据进行CRUD。 存储库不过是一种定制的数据处理方式。

Entities are generated via a console/terminal command: php app\console doctrine:generate:entity. The location of generated files is src/tr/rsywxBundle/Entity.

实体是通过控制台/终端命令生成的: php app\console doctrine:generate:entity 。 生成文件的位置是src/tr/rsywxBundle/Entity

更改位于的ORM映射文件 (Change the ORM mapping files located at)

src/tr/rsywxBundle/Resources/config/doctrine) and build mandatory functions like retrieving data to build a repository. For example:

src/tr/rsywxBundle/Resources/config/doctrine)并构建强制性功能,例如检索数据以构建存储库。 例如:


File location: src/tr/rsywxBundle/Resources/config/doctrine/BookBook.orm
tr\rsywxBundle\Entity\BookBook:
type: entity
repositoryClass: tr\rsywxBundle\Entity\BookRepository # Add this line to state that you will use BookRepository.php as the repository class for BookBook table
table: book_book
fields:
    ...

File location: src/tr/rsywxBundle/Resources/config/doctrine/BookBook.orm
tr\rsywxBundle\Entity\BookBook:
type: entity
repositoryClass: tr\rsywxBundle\Entity\BookRepository # Add this line to state that you will use BookRepository.php as the repository class for BookBook table
table: book_book
fields:
    ...

After that, run php app\console doctrine:generate:entity again. Now notice that a new BookRepository.php file is created under src/tr/rsywxBundle/Entity. Afterwards open that file and you will be able to create your own functions for data manipulation:

之后,再次运行php app \ console doctrine:generate:entity。 现在注意,在src/tr/rsywxBundle/Entity下创建了一个新的BookRepository.php文件。 然后打开该文件,您将能够创建自己的数据操作函数:


public function getResultAndCount($page, $rpp, $key=null) {
  // Get the book count
  $em = $this->getEntityManager();
  if ($key == 'null') {
    $q1 = $em->createQuery('select count(b.id) bc from trrsywxBundle:BookBook b');
  } else {
    $qstr = sprintf("select count(b.id) bc from trrsywxBundle:BookBook b where b.title like '%s%%'", $key);
    $q1 = $em->createQuery($qstr);
  }
  $res1 = $q1->getSingleResult();
  $count = $res1['bc'];
  // Now get the wanted result specified by page
  $repo = $em->getRepository('trrsywxBundle:BookBook');
  $q2 = $repo->createQueryBuilder('r')
    ->setMaxResults($rpp)
    ->setFirstResult(($page - 1) * $rpp)
    ->orderBy('r.id', 'desc');
  if ($key <> 'null') {
    $key = $key . '%';
    $q2->where('r.title like :key')
      ->setParameter('key', $key);
  }
  $q2 = $q2->getQuery();
  $res2 = $q2->getResult();
  return array($res2, $count);
}

public function getResultAndCount($page, $rpp, $key=null) {
  // Get the book count
  $em = $this->getEntityManager();
  if ($key == 'null') {
    $q1 = $em->createQuery('select count(b.id) bc from trrsywxBundle:BookBook b');
  } else {
    $qstr = sprintf("select count(b.id) bc from trrsywxBundle:BookBook b where b.title like '%s%%'", $key);
    $q1 = $em->createQuery($qstr);
  }
  $res1 = $q1->getSingleResult();
  $count = $res1['bc'];
  // Now get the wanted result specified by page
  $repo = $em->getRepository('trrsywxBundle:BookBook');
  $q2 = $repo->createQueryBuilder('r')
    ->setMaxResults($rpp)
    ->setFirstResult(($page - 1) * $rpp)
    ->orderBy('r.id', 'desc');
  if ($key <> 'null') {
    $key = $key . '%';
    $q2->where('r.title like :key')
      ->setParameter('key', $key);
  }
  $q2 = $q2->getQuery();
  $res2 = $q2->getResult();
  return array($res2, $count);
}

视图和模板 (Views and Templates)

Nothing can be represented without a view as a view is equivalent to a template according to the Symfony.

没有视图就无法表示任何内容,因为根据Symfony,视图等同于模板。

A template defines how your app would appear to the users. It is a text file that generates a text-based format. PHP template is one of the most popular templates that has a combination of PHP and text code.

模板定义了您的应用对用户的显示方式。 它是一个文本文件,可生成基于文本的格式。 PHP模板是结合了PHP和文本代码的最受欢迎的模板之一。

As an instance:

例如:


<!DOCTYPE html>
<html>
  <head>
    <title>Welcome to Symfony!</title>
  </head>
  <body>
    <h1><?php echo $page_title ?></h1>
    <ul id="navigation">
      <?php foreach ($navigation as $item): ?>
        <li>
          <a href="<?php echo $item->getHref() ?>">
            <?php echo $item->getCaption() ?>
          </a>
        </li>
      <?php endforeach ?>
    </ul>
  </body>
</html>

<!DOCTYPE html>
<html>
  <head>
    <title>Welcome to Symfony!</title>
  </head>
  <body>
    <h1><?php echo $page_title ?></h1>
    <ul id="navigation">
      <?php foreach ($navigation as $item): ?>
        <li>
          <a href="<?php echo $item->getHref() ?>">
            <?php echo $item->getCaption() ?>
          </a>
        </li>
      <?php endforeach ?>
    </ul>
  </body>
</html>

最终确定: (Finalizing:)

After bootstrapping and development the project is finalized with some advanced techniques like pagination, image watermarks etc.

自举和开发后,该项目将通过一些高级技术(如分页,图像水印等)完成。

图像水印 (Image watermarks)

Image watermarks refer to the display of image after processing which can be done as follows:

图像水印是指经过以下处理后的图像显示:


cover:
pattern: /books/cover/{id}_{title}_{author}_{width}.png
defaults: {_controller: trrsywxBundle:Default:cover, width: 300}

cover:
pattern: /books/cover/{id}_{title}_{author}_{width}.png
defaults: {_controller: trrsywxBundle:Default:cover, width: 300}

In a template, invoke the call to show the routed image by:

在模板中,通过以下方法调用调用以显示路由图像:


<imgsrc="{{path("cover", {'id':book.id, 'author':author, 'title':book.title}) }}" alt="{{book.title}}'s cover" title="{{book.title}}'s cover"/>

<imgsrc="{{path("cover", {'id':book.id, 'author':author, 'title':book.title}) }}" alt="{{book.title}}'s cover" title="{{book.title}}'s cover"/>

A processed image will be shown every time an image tag i.e. <img> comes across. This is not the complete set of tutorial from Symfony but a brief introduction that might help you make a wiser decision by choosing Symfony for building a web application for your use.

每次遇到图像标签即<img>时,都会显示已处理的图像。 这不是Symfony的完整教程集,而是简要的介绍,可以通过选择Symfony来构建供您使用的Web应用程序来帮助您做出更明智的决定。

翻译自: https://www.script-tutorials.com/building-a-web-app-using-symfony-2/

symfony2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值