教程4:使用 CRUDs

后端通常为用户提供表单让用户去操作数据。我们将继续之前的INVO的讲解,下面我们讲解CRUDs的使用,使用phalcon这个最基础的功能,我们讲能更加熟练的应用表单,验证,分页等功能。

Backends usually provides forms to allow users to manipulate data. Continuing the explanation of INVO, we now address the creation of CRUDs, a very common task that Phalcon will facilitate you using forms, validations, paginators and more.

使用 CRUD

在INVO(公司,产品,产品类型模块)中我们使用基础普通的 CRUD (创建,读取,更新和删除)操作。每个CRUD包含下面的文件:

Most options that manipulate data in INVO (companies, products and types of products), were developed using a basic and common CRUD (Create, Read, Update and Delete). Each CRUD contains the following files:

  1. invo/
  2. app/
  3. controllers/
  4. ProductsController.php
  5. models/
  6. Products.php
  7. forms/
  8. ProductsForm.php
  9. views/
  10. products/
  11. edit.volt
  12. index.volt
  13. new.volt
  14. search.volt

每个控制器包含下面的动作方法:

Each controller has the following actions:

  1. <?php
  2. class ProductsController extends ControllerBase
  3. {
  4. /**
  5. *动作开始显示“搜索”视图
  6. * The start action, it shows the "search" view
  7. */
  8. public function indexAction()
  9. {
  10. //...
  11. }
  12. /**
  13. * 从搜索页接受参数执行搜索并返回分页结果
  14. * Execute the "search" based on the criteria sent from the "index"
  15. * Returning a paginator for the results
  16. */
  17. public function searchAction()
  18. {
  19. //...
  20. }
  21. /**
  22. * 显示创建新商品视图
  23. * Shows the view to create a "new" product
  24. */
  25. public function newAction()
  26. {
  27. //...
  28. }
  29. /**
  30. * 显示编辑商品视图
  31. * Shows the view to "edit" an existing product
  32. */
  33. public function editAction()
  34. {
  35. //...
  36. }
  37. /**
  38. * 从新建商品接受参数并创建商品
  39. * Creates a product based on the data entered in the "new" action
  40. */
  41. public function createAction()
  42. {
  43. //...
  44. }
  45. /**
  46. * 根据在编辑视图输入的数据更新产品信息
  47. * Updates a product based on the data entered in the "edit" action
  48. */
  49. public function saveAction()
  50. {
  51. //...
  52. }
  53. /**
  54. * 删除一个现有的商品
  55. * Deletes an existing product
  56. */
  57. public function deleteAction($id)
  58. {
  59. //...
  60. }
  61. }

搜索表单

每一个CRUD始于一个搜索表单。这张表单显示了(产品)表中的每个字段,允许用户从任何字段创建一个搜索条件。“products”表和“products_types”表有关联。在这种情况下,为了方便搜索的字段,我们先查询表“products_types”中的记录:

Every CRUD starts with a search form. This form shows each field that has the table (products), allowing the user to create a search criteria from any field. Table “products” has a relationship to the table “products_types”. In this case, we previously queried the records in this table in order to facilitate the search by that field:

  1. <?php
  2. /**
  3. * The start action, it shows the "search" view
  4. */
  5. public function indexAction()
  6. {
  7. $this->persistent->searchParams = null;
  8. $this->view->form = new ProductsForm;
  9. }

ProductsForm (app/forms/ProductsForm.php)实例被传递给视图。这个表单定义了用户可见的字段。

An instance of the form ProductsForm (app/forms/ProductsForm.php) is passed to the view. This form defines the fields that are visible to the user:

  1. <?php
  2. use Phalcon\Forms\Form;
  3. use Phalcon\Forms\Element\Text;
  4. use Phalcon\Forms\Element\Hidden;
  5. use Phalcon\Forms\Element\Select;
  6. use Phalcon\Validation\Validator\Email;
  7. use Phalcon\Validation\Validator\PresenceOf;
  8. use Phalcon\Validation\Validator\Numericality;
  9. class ProductsForm extends Form
  10. {
  11. /**
  12. * Initialize the products form
  13. */
  14. public function initialize($entity = null, $options = array())
  15. {
  16. if (!isset($options['edit'])) {
  17. $element = new Text("id");
  18. $this->add($element->setLabel("Id"));
  19. } else {
  20. $this->add(new Hidden("id"));
  21. }
  22. $name = new Text("name");
  23. $name->setLabel("Name");
  24. $name->setFilters(array('striptags', 'string'));
  25. $name->addValidators(array(
  26. new PresenceOf(array(
  27. 'message' => 'Name is required'
  28. ))
  29. ));
  30. $this->add($name);
  31. $type = new Select('profilesId', ProductTypes::find(), array(
  32. 'using' => array('id', 'name'),
  33. 'useEmpty' => true,
  34. 'emptyText' => '...',
  35. 'emptyValue' => ''
  36. ));
  37. $this->add($type);
  38. $price = new Text("price");
  39. $price->setLabel("Price");
  40. $price->setFilters(array('float'));
  41. $price->addValidators(array(
  42. new PresenceOf(array(
  43. 'message' => 'Price is required'
  44. )),
  45. new Numericality(array(
  46. 'message' => 'Price is required'
  47. ))
  48. ));
  49. $this->add($price);
  50. }
  51. }

表单中的元素基于 forms 组件并以面向对象方式声明,几乎每个元素遵循相同的结构:

The form is declared using an object-oriented scheme based on the elements provided by the forms component. Every element follows almost the same structure:

  1. <?php
  2. // Create the element
  3. $name = new Text("name");
  4. // Set its label
  5. $name->setLabel("Name");
  6. // Before validating the element apply these filters
  7. $name->setFilters(array('striptags', 'string'));
  8. // Apply this validators
  9. $name->addValidators(array(
  10. new PresenceOf(array(
  11. 'message' => 'Name is required'
  12. ))
  13. ));
  14. // Add the element to the form
  15. $this->add($name);

其他元素也使用这种形式:

Other elements are also used in this form:

  1. <?php
  2. // Add a hidden input to the form
  3. $this->add(new Hidden("id"));
  4. // ...
  5. // Add a HTML Select (list) to the form
  6. // and fill it with data from "product_types"
  7. $type = new Select('profilesId', ProductTypes::find(), array(
  8. 'using' => array('id', 'name'),
  9. 'useEmpty' => true,
  10. 'emptyText' => '...',
  11. 'emptyValue' => ''
  12. ));

注意ProductTypes:find()包含必要的数据来填充 Phalcon\Tag::select 中的SELECT标记。当表单传递到视图,它可以被渲染后并呈现给用户:

Note that ProductTypes::find() contains the data necessary to fill the SELECT tag using Phalcon\Tag::select. Once the form is passed to the view, it can be rendered and presented to the user:

  1. {{ form("products/search") }}
  2. <h2>Search products</h2>
  3. <fieldset>
  4. {% for element in form %}
  5. <div class="control-group">
  6. {{ element.label(['class': 'control-label']) }}
  7. <div class="controls">{{ element }}</div>
  8. </div>
  9. {% endfor %}
  10. <div class="control-group">
  11. {{ submit_button("Search", "class": "btn btn-primary") }}
  12. </div>
  13. </fieldset>

这生成了以下HTML:

This produces the following HTML:

  1. <form action="/invo/products/search" method="post">
  2. <h2>Search products</h2>
  3. <fieldset>
  4. <div class="control-group">
  5. <label for="id" class="control-label">Id</label>
  6. <div class="controls"><input type="text" id="id" name="id" /></div>
  7. </div>
  8. <div class="control-group">
  9. <label for="name" class="control-label">Name</label>
  10. <div class="controls">
  11. <input type="text" id="name" name="name" />
  12. </div>
  13. </div>
  14. <div class="control-group">
  15. <label for="profilesId" class="control-label">profilesId</label>
  16. <div class="controls">
  17. <select id="profilesId" name="profilesId">
  18. <option value="">...</option>
  19. <option value="1">Vegetables</option>
  20. <option value="2">Fruits</option>
  21. </select>
  22. </div>
  23. </div>
  24. <div class="control-group">
  25. <label for="price" class="control-label">Price</label>
  26. <div class="controls"><input type="text" id="price" name="price" /></div>
  27. </div>
  28. <div class="control-group">
  29. <input type="submit" value="Search" class="btn btn-primary" />
  30. </div>
  31. </fieldset>

当提交表单时,控制器中“搜索”方法根据用户输入的数据执行搜索。

When the form is submitted, the action “search” is executed in the controller performing the search based on the data entered by the user.

执行搜索

“search”方法具有双重的行为。当通过POST访问时,它执行一个基于接受数据的搜索。但是当通过GET访问的时候,它移动分页器paginator中当前的页面。为了区分请求的HTTP方法,我们使用 Request 组件来进行检查:

The action “search” has a dual behavior. When accessed via POST, it performs a search based on the data sent from the form. But when accessed via GET it moves the current page in the paginator. To differentiate one from another HTTP method, we check it using the Request component:

  1. <?php
  2. /**
  3. * Execute the "search" based on the criteria sent from the "index"
  4. * Returning a paginator for the results
  5. */
  6. public function searchAction()
  7. {
  8. if ($this->request->isPost()) {
  9. //create the query conditions
  10. } else {
  11. //paginate using the existing conditions
  12. }
  13. //...
  14. }

使用 Phalcon\Mvc\Model\Criteria 我们可以基于从表单发送的数据类型和值智能的创建搜索条件:

With the help of Phalcon\Mvc\Model\Criteria, we can create the search conditions intelligently based on the data types and values sent from the form:

  1. <?php
  2. $query = Criteria::fromInput($this->di, "Products", $this->request->getPost());

这个方法验证不是”“(空字符串)和null的值,并由这些值创建搜索条件:

This method verifies which values are different from “” (empty string) and null and takes them into account to create the search criteria:

  • 如果字段类型是文本或者是相似类型(char, varchar, text, etc.)。使用SQL “like”操作去过滤结果。
  • 如果数据类型不是文本或者相关的,就使用”=”操作。
  • If the field data type is text or similar (char, varchar, text, etc.) It uses an SQL “like” operator to filter the results.
  • If the data type is not text or similar, it’ll use the operator “=”.

此外,“Criteria”忽略了$_POST中所有不匹配表中的任何字段的变量。值使用“约束参数值”自动进行了转义。

Additionally, “Criteria” ignores all the $_POST variables that do not match any field in the table. Values are automatically escaped using “bound parameters”.

现在我们将在控制器的会话袋中存储产生的参数:

Now, we store the produced parameters in the controller’s session bag:

  1. <?php
  2. $this->persistent->searchParams = $query->getParams();

会话袋是在请求之间持续使用会话服务的控制器中的一个特殊的属性。访问时,:doc:Phalcon\Session\Bag <../api/Phalcon_Session_Bag> 实例注入到该属性 ,并在每个控制器中独立。

A session bag, is a special attribute in a controller that persists between requests using the session service. When accessed, this attribute injects a Phalcon\Session\Bag instance that is independent in each controller.

然后,基于构建的参数我们执行查询:

Then, based on the built params we perform the query:

  1. <?php
  2. $products = Products::find($parameters);
  3. if (count($products) == 0) {
  4. $this->flash->notice("The search did not found any products");
  5. return $this->forward("products/index");
  6. }

如果搜索不到任何产品,我们引导用户返回首页。假设搜索返回了结果,然后我们创建一个分页器paginator来轻松导航:

If the search doesn’t return any product, we forward the user to the index action again. Let’s pretend the search returned results, then we create a paginator to navigate easily through them:

  1. <?php
  2. use Phalcon\Paginator\Adapter\Model as Paginator;
  3. // ...
  4. $paginator = new Paginator(array(
  5. "data" => $products, // Data to paginate
  6. "limit" => 5, // Rows per page
  7. "page" => $numberPage // Active page
  8. ));
  9. // Get active page in the paginator
  10. $page = $paginator->getPaginate();

最后,我们将返回页面输出到视图:

Finally we pass the returned page to view:

  1. <?php
  2. $this->view->page = $page;

(app/views/products/search.phtml)在视图中,我们遍历对应于当前页面的每一条结果显示给当前用户:

In the view (app/views/products/search.phtml), we traverse the results corresponding to the current page, showing every row in the current page to the user:

  1. {% for product in page.items %}
  2. {% if loop.first %}
  3. <table>
  4. <thead>
  5. <tr>
  6. <th>Id</th>
  7. <th>Product Type</th>
  8. <th>Name</th>
  9. <th>Price</th>
  10. <th>Active</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. {% endif %}
  15. <tr>
  16. <td>{{ product.id }}</td>
  17. <td>{{ product.getProductTypes().name }}</td>
  18. <td>{{ product.name }}</td>
  19. <td>{{ "%.2f"|format(product.price) }}</td>
  20. <td>{{ product.getActiveDetail() }}</td>
  21. <td width="7%">{{ link_to("products/edit/" ~ product.id, 'Edit') }}</td>
  22. <td width="7%">{{ link_to("products/delete/" ~ product.id, 'Delete') }}</td>
  23. </tr>
  24. {% if loop.last %}
  25. </tbody>
  26. <tbody>
  27. <tr>
  28. <td colspan="7">
  29. <div>
  30. {{ link_to("products/search", 'First') }}
  31. {{ link_to("products/search?page=" ~ page.before, 'Previous') }}
  32. {{ link_to("products/search?page=" ~ page.next, 'Next') }}
  33. {{ link_to("products/search?page=" ~ page.last, 'Last') }}
  34. <span class="help-inline">{{ page.current }} of {{ page.total_pages }}</span>
  35. </div>
  36. </td>
  37. </tr>
  38. </tbody>
  39. </table>
  40. {% endif %}
  41. {% else %}
  42. No products are recorded
  43. {% endfor %}

在上面的例子中有很多东西值得详细深入。首先,在当前页面遍历项目使用Volt的“for”。Volt提供了一个简单的语法实现一个PHP foreach。

There are many things in the above example that worth detailing. First of all, active items in the current page are traversed using a Volt’s ‘for’. Volt provides a simpler syntax for a PHP ‘foreach’.

  1. {% for product in page.items %}

在PHP是一样的:

Which in PHP is the same as:

  1. <?php foreach ($page->items as $product) { ?>

整个的“for”块如下所示:

The whole ‘for’ block provides the following:

{% for product in page.items %}

  • {% if loop.first %}

    Executed before the first product in the loop

    {% endif %}

    Executed for every product of page.items

    {% if loop.last %}

    Executed after the last product is loop

{% endif %}

{% else %}

Executed if page.items does not have any products

{% endfor %}

现在我们可以返回到视图和找出每一块代码做什么。每一个在“产品”中的字段打印相应信息:

Now you can go back to the view and find out what every block is doing. Every field in “product” is printed accordingly:

  1. <tr>
  2. <td>{{ product.id }}</td>
  3. <td>{{ product.productTypes.name }}</td>
  4. <td>{{ product.name }}</td>
  5. <td>{{ "%.2f"|format(product.price) }}</td>
  6. <td>{{ product.getActiveDetail() }}</td>
  7. <td width="7%">{{ link_to("products/edit/" ~ product.id, 'Edit') }}</td>
  8. <td width="7%">{{ link_to("products/delete/" ~ product.id, 'Delete') }}</td>
  9. </tr>

正如我们之前看到的一样,使用product.id和在PHP中使用:$product->id是一样的,我们使用product.name是一样的。在其他地方渲染是不相同的,例如,product.productTypes.name。要理解这部分,我们必须看下products模型(app/models/Products.php):

As we seen before using product.id is the same as in PHP as doing: $product->id, we made the same with product.name and so on. Other fields are rendered differently, for instance, let’s focus in product.productTypes.name. To understand this part, we have to check the model Products (app/models/Products.php):

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. /**
  4. * Products
  5. */
  6. class Products extends Model
  7. {
  8. // ...
  9. /**
  10. * Products initializer
  11. */
  12. public function initialize()
  13. {
  14. $this->belongsTo('product_types_id', 'ProductTypes', 'id', array(
  15. 'reusable' => true
  16. ));
  17. }
  18. // ...
  19. }

一个模型,可以有一个名为“initialize”的方法,这种方法每次请求都会被调用一次来初始化一个ORM数据模型。在这种情况下,“Products”是通过初始化定义,模型有一对多关系到另一个“ProductTypes”模型。

A model, can have a method called “initialize”, this method is called once per request and it serves the ORM to initialize a model. In this case, “Products” is initialized by defining that this model has a one-to-many relationship to another model called “ProductTypes”.

  1. <?php
  2. $this->belongsTo('product_types_id', 'ProductTypes', 'id', array(
  3. 'reusable' => true
  4. ));

这意味着,Products中的属性“product_types_id”有一个一对多的关系到”ProductTypes”模型中的”id”属性。通过定义这种关系我们可以访问产品的类型名称使用如下方式:

Which means, the local attribute “product_types_id” in “Products” has an one-to-many relation to the model “ProductTypes” in its attribute “id”. By defining this relation we can access the name of the product type by using:

  1. <td>{{ product.productTypes.name }}</td>

“price”输出使用Volt过滤器格式:

The field “price” is printed by its formatted using a Volt filter:

  1. <td>{{ "%.2f"|format(product.price) }}</td>

在PHP实现是:

What in PHP would be:

  1. <?php echo sprintf("%.2f", $product->price) ?>

是否输出产品信息使用的是模型的辅助实现:

Printing whether the product is active or not uses a helper implemented in the model:

  1. <td>{{ product.getActiveDetail() }}</td>

该方法在模型中的定义:

This method is defined in the model:

创建和更新记录

现在让我们看看CRUD是如何创建和更新记录。由用户从“new”和“edit”视图输入的数据,被发送到动作方法“create”和“save”,执行“creating”和“updating”操作产品。

Now let’s see how the CRUD creates and updates records. From the “new” and “edit” views the data entered by the user are sent to the actions “create” and “save” that perform actions of “creating” and “updating” products respectively.

在创建的情况下,我们拿到提交的数据,并将它们分配给一个新的“products”实例:

In the creation case, we recover the data submitted and assign them to a new “products” instance:

  1. <?php
  2. /**
  3. * Creates a new product
  4. */
  5. public function createAction()
  6. {
  7. if (!$this->request->isPost()) {
  8. return $this->forward("products/index");
  9. }
  10. $form = new ProductsForm;
  11. $product = new Products();
  12. // ...
  13. }

还记得我们在产品表单中定义的过滤器吗?数据在被分配给$product对象之前进行了过滤。这种过滤是可选的,ORM也转义了输入的数据并根据列类型执行了额外的数据转换:

Remember the filters we defined in the Products form? Data is filtered before being assigned to the object $product. This filtering is optional, also the ORM escapes the input data and performs additional casting according to the column types:

  1. <?php
  2. // ...
  3. $name = new Text("name");
  4. $name->setLabel("Name");
  5. // Filters for name
  6. $name->setFilters(array('striptags', 'string'));
  7. // Validators for name
  8. $name->addValidators(array(
  9. new PresenceOf(array(
  10. 'message' => 'Name is required'
  11. ))
  12. ));
  13. $this->add($name);

当我们保存数据的时候我们会知道数据是否符合业务规则和在ProductsForm (app/forms/ProductsForm.php)中实现的验证规则:

When saving we’ll know whether the data conforms to the business rules and validations implemented in the form ProductsForm (app/forms/ProductsForm.php):

  1. <?php
  2. // ...
  3. $form = new ProductsForm;
  4. $product = new Products();
  5. // Validate the input
  6. $data = $this->request->getPost();
  7. if (!$form->isValid($data, $product)) {
  8. foreach ($form->getMessages() as $message) {
  9. $this->flash->error($message);
  10. }
  11. return $this->forward('products/new');
  12. }

最后,如果表单不返回任何验证信息我们可以保存产品实例:

Finally, if the form does not return any validation message we can save the product instance:

  1. <?php
  2. // ...
  3. if ($product->save() == false) {
  4. foreach ($product->getMessages() as $message) {
  5. $this->flash->error($message);
  6. }
  7. return $this->forward('products/new');
  8. }
  9. $form->clear();
  10. $this->flash->success("Product was created successfully");
  11. return $this->forward("products/index");

在更新产品的时候,首先我们必须向用户展示当前正在编辑的数据记录:

Now, in the case of product updating, first we must present to the user the data that is currently in the edited record:

  1. <?php
  2. /**
  3. * Edits a product based on its id
  4. */
  5. public function editAction($id)
  6. {
  7. if (!$this->request->isPost()) {
  8. $product = Products::findFirstById($id);
  9. if (!$product) {
  10. $this->flash->error("Product was not found");
  11. return $this->forward("products/index");
  12. }
  13. $this->view->form = new ProductsForm($product, array('edit' => true));
  14. }
  15. }

绑定到表单的数据被为第一个参数传递给模型。由于这一点,用户可以改变任何值,然后通过“save”保存到数据库:

The data found is bound to the form passing the model as first parameter. Thanks to this, the user can change any value and then sent it back to the database through to the “save” action:

  1. <?php
  2. /**
  3. * Saves current product in screen
  4. *
  5. * @param string $id
  6. */
  7. public function saveAction()
  8. {
  9. if (!$this->request->isPost()) {
  10. return $this->forward("products/index");
  11. }
  12. $id = $this->request->getPost("id", "int");
  13. $product = Products::findFirstById($id);
  14. if (!$product) {
  15. $this->flash->error("Product does not exist");
  16. return $this->forward("products/index");
  17. }
  18. $form = new ProductsForm;
  19. $data = $this->request->getPost();
  20. if (!$form->isValid($data, $product)) {
  21. foreach ($form->getMessages() as $message) {
  22. $this->flash->error($message);
  23. }
  24. return $this->forward('products/new');
  25. }
  26. if ($product->save() == false) {
  27. foreach ($product->getMessages() as $message) {
  28. $this->flash->error($message);
  29. }
  30. return $this->forward('products/new');
  31. }
  32. $form->clear();
  33. $this->flash->success("Product was updated successfully");
  34. return $this->forward("products/index");
  35. }

我们已经看到使用Phalcon如何创建表单并从数据库中以结构化的方式绑定数据。在下一章,我们将看到如何添加自定义的HTML元素,比如,菜单。

We have seen how Phalcon lets you create forms and bind data from a database in a structured way. In next chapter, we will see how to add custom HTML elements like a menu.