ป้ายกำกับ: คอนฟิก

CodeIgniter: แยก configCodeIgniter: แยก config

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

PHP

PHP

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

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

PHP

PHP

<?php
defined ('BASEPATH') OR exit ('No direct script access allowed') ; $config&#x5B;'caching']&#x5B;'adapter'] = 'memcached';
$config&#x5B;'caching']&#x5B;'backup'] = 'file';

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

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

    PHP

    PHP

    $autoload['config']
    

    เช่น

    PHP

    PHP

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

    PHP

    PHP

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

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

    PHP

    PHP

    <?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) , '
    

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