Site icon PlusMagi's Blog By Pitt Phunsanit

CodeIgniter: แยก config

การดึงค่าคอนฟิกของโค้ทอินิกเตอร์สามารถทำได้โดย ใช้คำสั่ง

$this->config->item (' ตัวแปร ') ;

โดยจะดึงมาจากไฟล์ \application\config\config.php เป็นหลัก แต่ถ้าต้องการแยก config ออกมาเป็นส่วน ๆ เพื่อความง่ายในการจัดการ สามารถสร้างไฟล์ ขึ้นมาใน application\config ได้

<?php
defined ('BASEPATH') OR exit ('No direct script access allowed') ;

$config['caching']['adapter'] = 'memcached';
$config['caching']['backup'] = 'file';

จากนั้นเราจะอ่าน configuration เข้ามาในระบบของเราสามารถทำได้ 2 วิธีคือ

  1. เป็นค่าที่เราต้องใช้บ่อย ๆ แทบทุกหน้า เพิ่มเข้าไปใน Auto-loading เปิดไฟล์ \application\config\autoload.php เพิ่มชื่อไฟล์ลงไปใน
    $autoload['config']

    เช่น

    ...
    $autoload['config'] = ['caching'];
    ...
  2. ถ้าต้องการใช้เฉพาะบางไฟล์ ทำได้โดยการ load ใน controller ที่ต้องการโดยใช้คำสั่ง
    ...
    $this->config->load ('caching') ;
    ...

ผมใช้หน้าแรกแสดงตัวอย่างการใช้

<?php
defined ('BASEPATH') or exit ('No direct script access allowed') ;

class Welcome extends CI_Controller
{
 public function __construct () {
 parent::__construct () ;

 echo 'charset = ' . $this->config->item ('charset') ;

 //$this->config->load ('caching') ;

 echo '<pre>', print_r ($this->config->item ('caching') , true) , '</pre>';
 }
...

อ่านเพิ่มเติม

Exit mobile version