顯示具有 hook 標籤的文章。 顯示所有文章
顯示具有 hook 標籤的文章。 顯示所有文章

2012年7月2日 星期一

解決 Codeigniter 的 display_override hook 與 Disucz X2.5 衝突

為了能夠在 CI 中,取得 Discuz $_G 這個超級變數,我把 /source/class/class_core.php 直接載入了 CI 作為一個 Librarries。

在 CodeIgniter 中整合 Discuz X2.5, 引用超級變數 $_G 來獲取用戶名, uid等資訊.


但由於 Discuz X2.5 有自己的一套 input、output 機制,導致於我為 CI 所撰寫的  $hook['display_override']​  會沒有反應。


這是因為 discuz 把 ob_start 設為 NULL 了,使得 $CI->output->get_output() 取不到半點字串。

為了讓它能夠正常運作,採用了一個較直接的思路:
「如果目前沒有瀏覽著論壇,則不呼叫 disucz 的 _init_output 方法」

if ( ! strpos($_SERVER['REQUEST_URI'], 'bbs') ) $this->is_in_bbs = false;​
...
if ($this->is_in_bbs) $this->_init_output();​

再觀察看看有沒有其它問題...

2012年6月22日 星期五

為 CodeIgniter 掛載 hook 將網頁所有 img tag 自動補足 alt 屬性

此操作引用了 simple_html_dom 類庫。

本 hook 將可以為 CI 中,所有輸出的網頁裡的 <img> 自動作補足 alt 屬性的操作,提升 SEO 效果。例如原始 view 中的程式碼為:
    <div class="img_slide">
        <img src="a1.png" alt="第一章">
        <img src="a2.png" alt="">
        <img src="a3.png" alt="呵呵">
        <img src="a4.png" alt="第四章 - 你的網站名稱">
    </div>
透過此 hook 後,用戶及搜尋引擎將會在瀏覽器中見到如下:
    <div class="img_slide">
        <img src="a1.png" alt="第一章 - 你的網站名稱">
        <img src="a2.png" alt="你的網站名稱">
        <img src="a3.png" alt="呵呵 - 你的網站名稱">
        <img src="a4.png" alt="第四章 - 你的網站名稱">
    </div>

1.
打開檔案:
    \application\config\config.php
搜尋:
    $config['enable_hooks']
確保它為:
    $config['enable_hooks'] = TRUE;​


2.
打開檔案:
    \application\config\hooks.php
任意空白處插入程式碼:
    // 處理<img>缺省alt=""
    $hook['display_override'][] = array(
        'class'    => '',
        'function' => 'images_auto_set_alt',
        'filename' => 'output.php',
        'filepath' => 'hooks',
        'params'   => array( 'output_display' => TRUE )
    );​


3.
新增檔案: \application\hooks\output.php
    /**
     * 將輸出的 圖片(<img>) 進行處理;自動配置 alt 屬性。
     *
     * @param array   $setting=array() 設定
     *                $setting['output_display'] => 是否直接輸出給瀏覽器。FALSE代表不直接輸出,僅回存至buffer。
     * @return NULL                    不會回傳東西。
     */
    function images_auto_set_alt( $setting=array() ) {
        $CI =& get_instance();
        $CI->load->library( 'simple_html_dom' ); // require_once APPPATH . 'libraries/simple_html_dom.php';
        $buffer = $CI->output->get_output();

        $DOM = str_get_html( $buffer );
        foreach ( $DOM->find( 'img' ) as $key => $img ) {
            if ( empty( $img->alt ) && ! strpos( $img->alt, $CI->config->item( 'site_name' ) ) ) {
                $img->alt = $CI->config->item( 'site_name' );
            }
            else {
                $img->alt .= ' - ' . $CI->config->item( 'site_name' );
            }
        }

        $CI->output->set_output( $DOM->save() );

        if ( $setting['output_display'] ) {
            $CI->output->_display();
        }
    }


4.
完成!