วันอังคารที่ 11 พฤศจิกายน พ.ศ. 2557

Yii แยก backend frontend แบบง่าย

หากเราอยากจะทำ backend, frontend ที่แยก theme และ login กันอย่างชัดเจน yii สามารถทำได้หลายแบบ หัวข้อนี้จะเอาวิธีง่ายๆ ซึ่งกว่ากระผมจะได้มานั้น งมผิดๆ ถูกๆ มา 2 วันเต็ม ขอบอกตรงนี้เลยว่า มันต้องใช้พลังเยอะจริงๆ - -"
ปล.อาจจะ งงกับคำว่า backend, admin หน่อยนะครับ เพราะรูปที่แคปไว้คนละช่วงเวลากัน คิดซะกว่าเป็น admin หมดละกันนะ

หัวข้อทั้งหมด
- Generate admin module
- Initial module (ตั้งค่า  component, layout path, theme)
- ประกาศใช้ module admin



Direction structor






































Generate admin module
ส่วนนี้ใช้ gii ช่วยสร้าง admin module ส่วนใครแนว hardcore จะสร้างเองก็ได้นะ 555


Initial module
จากที่เรา generate module เรียบร้อยแล้ว จะได้ AdminModule.php มา พร้อม extend CWebModule โค้ดที่ได้มาตอนแรกจะได้แบบนี้


// [webroot]/protected/modules/admin/AdminModule.php
...

public function init()
{
 // this method is called when the module is being created
 // you may place code here to customize the module or the application

 // import the module-level models and components
 $this->setImport(array(
  'admin.models.*',
  'admin.components.*',
 ));
}

public function beforeControllerAction($controller, $action)
{
 if(parent::beforeControllerAction($controller, $action))
 {
  // this method is called before any module controller action is performed
  // you may place customized code here
  return true;
 }
 else
  return false;
}

...

เราก็จะ config เพิ่มเติมพวก theme, layout, path layout และ component



...

public function init()
{
  ...

  Yii::app()->setComponents(array(
    'errorHandler' => array(
        'errorAction' => 'admin/home/error',
    ),
    'user' => array(
        'class' => 'CWebUser',
        'stateKeyPrefix' => '_admin',
        'loginUrl' => 'admin/home/login',
    ),
  ));

  /*-- default theme --*/
  Yii::app()->theme = 'xxx';
  $this->setLayoutPath(Yii::getPathOfAlias('admin.views.layouts'));

...

component user นั้นจะใช้ในกรณี login เหมือนกันกับ config ในไฟล์ main.php เพียงแต่เราจะแยกหน้าล็อคอินของ frontend, backend ออกจากกัน


...

public function beforeControllerAction($controller, $action)
{
 if(parent::beforeControllerAction($controller, $action))
 {
  // this method is called before any module controller action is performed
  // you may place customized code here

  /*-- default layout --*/
  $controller->layout = 'main';

  $route = $controller->id . '/' . $action->id;
  $publicPages = array(
            'home/login',
            'home/error',
        );

  return true;
 }
 else
  return false;
}

...

ประกาศใช้ module admin
เราจะทำการเรียกใช้โมดูล admin ซึ่งเรียกได้ง่ายๆ โดยเข้าไปที่ [webroot]/protected/config/main.php

...

return array(
    'modules'=>array(
        'admin',
    ),
    ......
);

...

เพียงเท่านี้ก็สามารถใช้งานได้แล้วครับ ส่วนการตั้งค่านอกเหนือจากนี้ สามารถเข้าไปอ่านข้อมูลเพิ่มเติมของ CWebModule

ไม่มีความคิดเห็น:

แสดงความคิดเห็น