Hiển thị các bài đăng có nhãn Symfony. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Symfony. Hiển thị tất cả bài đăng

Thứ Bảy, 18 tháng 5, 2013

Shell For Symfony 2

I. SETTING UP
1. set virtual host
# /etc/httpd/conf/httpd.conf
NameVirtualHost 127.0.0.1
 <VirtualHost 127.0.0.1>
  ServerName symblog.dev
  DocumentRoot "/var/www/html/symblog.dev/web"
  DirectoryIndex app.php
  <Directory "/var/www/html/symblog.dev/web">
    AllowOverride All
    Allow from All
  </Directory>
</VirtualHost>
2. set hosts
# /etc/hosts
127.0.0.1     symblog.dev
3. set permission app/cache and app/logs
chmod 777 cache 
chmod 777 logs 
  
II. CREATE BUNDLE

c:\wamp\www\jobeetsymfony2.com>php app/console generate:bundle --namespace=Blogg
er/Bundle --format=yml

  Welcome to the Symfony2 bundle generator
In your code, a bundle is often referenced by its name. It can be the
concatenation of all namespace parts but it's really up to you to come
up with a unique name (a good practice is to start with the vendor name).
Based on the namespace, we suggest BloggerBundle.

Bundle name [BloggerBundle]: BloggerBundle
The bundle can be generated anywhere. The suggested default directory uses
the standard conventions.

Target directory [C:/wamp/www/jobeetsymfony2.com/src]: C:/wamp/www/jobeetsymfony
2.com/src
To help you get started faster, the command can generate some
code snippets for you.

Do you want to generate the whole directory structure [no]? y
  Summary before generation
You are going to generate a "Blogger\Bundle\BloggerBundle" bundle
in "C:/wamp/www/jobeetsymfony2.com/src/" using the "yml" format.

Do you confirm generation [yes]? y
  Bundle generation
Generating the bundle code: OK
Checking that the bundle is autoloaded: OK

Confirm automatic update of your Kernel [yes]? y
Enabling the bundle inside the Kernel: OK

Confirm automatic update of the Routing [yes]? y
Importing the bundle routing resource: OK
  You can now start using the generated code!


III. ASSETS - symlinks for public pakage in src folder to web folder
php app/console assets:install web --symlink
 
If you are using an Operating System that doesn’t support symlinks such as
Windows you will need to drop the symlink option as follows.
php app/console assets:install web
This method will actually copy the resources from the bundles public folder into the
applications web folder. As the files are actually copied, you will need to run
this task every time you make a change to a bundles public resource. 


IV. GENERATE ENTITIES
php app/console doctrine:generate:entities Blogger
 

V. DATABASES
create database : php app/console doctrine:database:create
create table : php app/console doctrine:schema:create
 
Next update the vendors to reflect these changes.
composer install
composer update 
http://getcomposer.org/doc/00-intro.md#installation-windows 
In Linux : - get composer : curl -sS https://getcomposer.org/installer | php
           - install composer : php composer.phar install
 
 
add example data : php app/console doctrine:fixtures:load
 

***Doctrine 2 Migrations

The Doctrine 2 Migrations extension and bundle do not come with the Symfony2 Standard Distribution, we need to manually install them as we did with the Data Fixtures extension and bundle. Open up the composer.json file located in the project root and add the Doctrine 2 Migrations extension and bundle to it as follows.
"require": {
    // ...
    "doctrine/doctrine-migrations-bundle": "dev-master",
    "doctrine/migrations": "dev-master"
}
Next update the vendors to reflect these changes.

composer update 
 
This will pull down the latest version of each of the repositories from GitHub and install them to the required locations.
Now let’s register the bundle in the kernel located at app/AppKernel.php.
// app/AppKernel.php
public function registerBundles()
{
    $bundles = array(
        // ...
        new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
        // ...
    );
    // ...
}
We are now ready to update the database to reflect the entity changes. This is a 2 step process. First we need to get Doctrine 2 Migrations to work out the differences between the entities and the current database schema. This is done with the doctrine:migrations:diff task. Secondly we need to actually perform the migration based on the previously created diff. This is done with the doctrine:migrations:migrate task.
Run the following 2 commands to update the database schema.
$ php app/console doctrine:migrations:diff
$ php app/console doctrine:migrations:migrate
Your database will now reflect the latest entity changes and contain the new comment table.


 
VI. CREATE DOCTRINE REPOSITORY
php app/console doctrine:generate:entities Blogger\Bundle
php app/console doctrine:schema:update --force


VII. Adding Form Comments 

php app/console generate:doctrine:form BloggerBlogBundle:Comment

 

X.CLEAR CACHE 
c:\wamp\www\jobeetsymfony2.com>php app/console cache:clear --env=dev
Clearing the cache for the dev environment with debug true

c:\wamp\www\jobeetsymfony2.com>php app/console cache:clear --env=prod
Clearing the cache for the prod environment with debug false

Thứ Hai, 8 tháng 4, 2013

symfony 2



Special : http://tutorial.symblog.co.uk/
 
Cùng học Symfony 2 - Phần 1 - Cài đặt, model và CRUD


1  Tải về và cài đặt
Tải về “Symfony Standard” tại http://symfony.com/download
Giải nén → đổi tên thư mục Symfony thành sfdemo, sao chép vào thư mục “/var/www”
Mở tập tin “/etc/hosts”, thêm vào “127.0.0.1 sfdemo.t”
Tạo tập tin “/etc/apache2/sites-available/sfdemo.t” với nội dung như sau:
<VirtualHost *:80>
    ServerName sfdemo.t
    DocumentRoot /var/www/sfdemo/web
    DirectoryIndex app.php
    ErrorLog /var/www/logs/sfdemo-error.log
    CustomLog /var/www/logs/sfdemo-access.log combined
    <Directory "/var/www/sfdemo/web">
        AllowOverride All
        Allow from All
    </Directory>
</VirtualHost>

Chạy dòng lệnh:
sudo a2ensite sfdemo.t
sudo /etc/init.d/apache2 reload

Mở trình duyệt web với địa chỉ “http://sfdemo.t/app_dev.php”.

2  Tạo cơ sở dữ liệu, khu vực làm việc
Sửa thông tin kết nối CSDL tại “/var/www/sfdemo/app/config/parameters.yml”
Chạy các dòng lệnh sau:
cd /var/www/sfdemo
php app/console doctrine:database:create
php app/console generate:bundle --namespace=Aplus/DemoBundle --format=yml

   Trả lời một vài câu hỏi được đưa ra:
       Bundle namespace [Aplus/DemoBundle]: Aplus/DemoBundle
       Bundle name [AplusDemoBundle]: AplusDemoBundle
       Target directory [/var/www/sfdemo/src]: /var/www/sfdemo/src
       Configuration format (yml, xml, php, or annotation) [yml]: yml
       Do you want to generate the whole directory structure [no]? yes
       Do you confirm generation [yes]? yes
       Confirm automatic update of your Kernel [yes]? yes
       Confirm automatic update of the Routing [yes]? Yes
php app/console cache:clear

3  Tạo model
Chúng ta sẽ tạo 1 cái blog đơn giản với hai bảng là post và comment.

3.1  Phát sinh các entity
Tạo tập tin “/var/www/sfdemo/src/Aplus/DemoBundle/Resources/config/doctrine/Post.orm.yml” với nội dung:
Aplus\DemoBundle\Entity\Post:
  type: entity
  table: post
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    name:
      type: string
      length: 255
    title:
      type: string
      length: 255
    content:
      type: text
    created_at:
      type: datetime
    updated_at:
      type: datetime
  oneToMany:
    comment:
      targetEntity: Comment
      mappedBy: post

Tạo tập tin “/var/www/sfdemo/src/Aplus/DemoBundle/Resources/config/doctrine/Comment.orm.yml” với nội dung:
Aplus\DemoBundle\Entity\Comment:
  type: entity
  table: comment
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    commenter:
      type: string
      length: 255
    body:
      type: text
    post_id:
      type: integer
    created_at:
      type: datetime
    updated_at:
      type: datetime
  manyToOne:
    post:
      targetEntity: Post
      inversedBy: comment
      joinColumn:
        name: post_id
        referencedColumnName: id

Chạy lệnh sau:
   php app/console doctrine:generate:entities AplusDemoBundle
Lệnh trên sẽ tạo 2 file php tại /var/www/sfdemo/src/Aplus/DemoBundle/Entity
Nếu muốn cập nhật database, sửa ở các tập tin *.orm.yml trước, sau đó chạy lệnh sau:
   php app/console doctrine:schema:update --force

3.2  Viết các model của riêng mình
Sửa các tập tin *.orm.yml phía trên, bổ sung repositoryClass:
Aplus\DemoBundle\Entity\Post:
  type: entity
  repositoryClass: Aplus\DemoBundle\Repository\PostRepository

Chạy lệnh:
php app/console doctrine:generate:entities AplusDemoBundle
Lệnh trên sẽ tạo ra tập tin “/var/www/sfdemo/src/Aplus/DemoBundle/Repository/PostRepository.php” với nội dung:
<?php
namespace Aplus\DemoBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* PostRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class PostRepository extends EntityRepository
{
}

Thử tạo một hàm đơn giản thế này:
   function getPostList()
    {
        return array();
    }

Và chúng ta có thể gọi nó ở controller như bên dưới.
public function indexAction()
{
  $em = $this->getDoctrine()->getEntityManager();
        $entities = $em->getRepository('AplusDemoBundle:Post')->getPostList();
        return $this->render('AplusDemoBundle:Post:index.html.twig', array(
                    'entities' => $entities
                ));
}


4  Tạo view, controller và router
Có một cách đơn giản: tạo CRUD, hãy đọc code được tạo ra và hiểu sơ về nó trước.
php app/console doctrine:generate:crud --entity=AplusDemoBundle:Post --route-prefix=post --with-write --format=yml
php app/console cache:clear





-----------------------------------------------------------------------------------------------------------------------



Cùng học Symfony 2 - Phần 2 - view, controller và router



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;



Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...