Phần 2 - view, controller và router trong Symfony 2

Phần 2 - view, controller và router trong Symfony 2

4  Tạo View, Controller và Router

CRUD sẽ làm cho mọi thừ đơn giản, hãy dùng nó để bắt đầu việc ... đọc hiểu. Chạy các lệnh sau:
php app/console doctrine:generate:crud --entity=AplusDemoBundle:Post --route-prefix=post --with-write --format=yml
php app/console cache:clear

Với kiến trúc của Symfony2:

  • Model nằm ở /var/www/sfdemo/src/Aplus/DemoBundle/Entity
  • View nằm ở /var/www/sfdemo/src/Aplus/DemoBundle/Resources/views (Stylesheet, Image, và JavaScript nằm ở /var/www/sfdemo/src/Aplus/DemoBundle/Resources/views/public)
  • Controller nằm ở /var/www/sfdemo/src/Aplus/DemoBundle/Controller

4.1  View

Mặc định Symfony2 dùng template engine là Twig.

Twig định nghĩa 2 cú pháp đặc biệt:

{{ ... }}: "Says something": prints a variable or the result of an expression to the template;

{% ... %}: "Does something": a tag that controls the logic of the template; it is used to execute statements such as for-loops for example.

Với Twig, chúng ta có thể định nghĩa block. Twig block có thể chứa nội dung mặc định (xem title block bên dưới), nội dung mặc định này có thể được thay thế hoặc được kế thừa.

4.1.1  Layout

Tạo tập tin “/var/www/sfdemo/src/Aplus/DemoBundle/Resources/views/layout.html.twig” với nội dung:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>{% block title %}Demo Bundle{% endblock %}</title>
        <link rel="stylesheet" href="{{ asset('bundles/aplusdemo/css/style.css') }}" />
    </head>
    <body>
        <div id="wrapper">
            <div class="content">
                {% block content %}
                    This is a content block.
                {% endblock %}
            </div>
        </div>
    </body>
</html>

Ghi chú: Chúng ta có thể thay thế {% block content %} bằng {% block anything %}

4.1.2  Template

Một template cơ bản như sau:

{% extends 'AplusDemoBundle::layout.html.twig' %}
{% block content %}
<!-- original template code goes here -->
{% endblock %}
{% block xyz %}block xyz content{% endblock %}

Ghi chú:

  • <!-- original template code goes here --> sẽ thay thế nội dung mặc định của block.
  • Nếu muốn kế thừa thì thêm vào {{ parent() }}

4.2  Router

Xem router đã được tạo ra với câu lệnh phát sinh CRUD tại /var/www/sfdemo/src/Aplus/DemoBundle/Resources/config/routing/post.yml

Tập tin “/var/www/sfdemo/app/config/routing.yml” sẽ nhập các thiết lập từ “/var/www/sfdemo/src/Aplus/DemoBundle/Resources/config/routing/post.yml”. Hàm path bên dưới phát sinh ra url, với post_new được định nghĩa trong file routing.

<ul>
    <li>
        <a href="{{ path('post_new') }}">
            Create a new entry
        </a>
    </li>
</ul>

4.3  Controller

Xem controller được tạo ra với câu lệnh phát sinh CRUD tại: “/var/www/sfdemo/src/Aplus/DemoBundle/Controller/PostController.php”.
Giờ lấy ví dụ, chúng ta muốn tạo một yêu cầu ajax với

  • Url http://sfdemo.t/app_dev.php/post/delete-comment
  • Method: post

và muốn nhận kết quả là json với status (boolean:true||false) và message (string).

thì làm bằng cách nào?

  • Thêm “/delete-comment” với requirement method là post vào cuối tập tin  “/var/www/sfdemo/src/Aplus/DemoBundle/Resources/config/routing/post.yml”.
post_comment_delete:
    pattern:  /delete-comment
    defaults: { _controller: "AplusDemoBundle:Post:deletecomment" }
    requirements: { _method: post }
  • Tạo action tên deletemethod ở Post controller (/var/www/sfdemo/src/Aplus/DemoBundle/Controller/PostController.php), với nội dung đại loại như:
public function deletecommentAction()
    {
        $isAjax = $this->get('Request')->isXMLHttpRequest();
        if ($isAjax) {
            //...
            //return json
            $return = array(
                'status' => true,
                'msg' => 'Comment <b>xyz</b> has been deleted.'
            );
            return new Response(json_encode($return), 200, array('Content-Type' => 'application/json'));
        }
        return new Response('This is not ajax!', 400);
    }

Ghi chú: nhớ thêm vào tâp tin trên 1 dòng tham chiếu như bên dưới (bởi vì chúng ta sử dụng một class tên là Response):
use Symfony\Component\HttpFoundation\Response;

Bạn thấy bài viết này như thế nào?: 
Average: 5 (2 votes)
Ảnh của Khanh Hoang

Khanh Hoang - Kenn

Kenn is a user experience designer and front end developer who enjoys creating beautiful and usable web and mobile experiences.

Tìm kiếm bất động sản

 

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Cách vào Facebook, Facebook, Facebook Messenger, Facebook Timeline, Profile Facebook

Facebook đã “bốc hơi” mất 20 tỉ USD

Cổ phiếu Facebook đã giảm giá tới 18% khiến giá trị thị trường của mạng xã hội lớn nhất thế giới tiếp tục “bốc hơi” gần 20 tỉ USD.

www.OSTraining.com miễn phí 1 tháng học Drupal

www.OSTraining.com miễn phí 1 tháng học Drupal

Drupal Global Training Days is an initiative by the Drupal Association (D.A.) to introduce new and beginning users to Drupal.

Drupal 7

Tổ chức modules directory trong Drupal

Ever feel like your Drupal code is becoming a disorganised mess? Most Drupal sites contain a decent number of contributed modules

Công ty diệt chuột T&C

 

Diet con trung