路老闆個人品牌網站
0
  • 會員登入
  • 關於我們
    回主選單
    • 關於我們
  • 服務項目
  • 我的錄音小間
  • 課程活動
    回主選單
    • 線上課程
    • 預約服務
    • 活動報名
  • 商品總覽
  • 創作與紀錄
    回主選單
    • 部落格
    • 影像紀錄
    • Podcast
    • 我的作品
  • 最新消息
  • 聯絡我們
  • Join us
  • Login
  • 0
    路老闆個人品牌網站
  • 關於我們
    關於我們
  • 服務項目
  • 我的錄音小間
  • 課程活動
    線上課程 預約服務 活動報名
  • 商品總覽
  • 創作與紀錄
    部落格 影像紀錄 Podcast 我的作品
  • 最新消息
  • 聯絡我們
部落格
  • 文章總覽
  • 分類
  • 技術筆記
  • 日本旅遊
  • 網站搬家
  • 時事觀察
  • 投資理財
  • 公司經營
  • 主機架設
  • 接案
  • 遊戲心得
  • 產品開箱
  • 網頁相關
  • 金流串接
  • 遊戲經濟
  • 閒聊
  • 直銷
  • CodeIgniter
  • cpanel
  • 出書材料
  • 個人品牌
  • SEO
  • 讀書心得
  • 金流物流
  • 線上課程心得
  • 日劇
    • 大河劇
      • 真田丸
  • AI
91app ClubHouse php8 imunify360 cdn apache php nginx linode digitalocean
  1. 首頁
  2. 部落格
  3. CodeIgniter 避免 controller 與 model 命名衝突

CodeIgniter 避免 controller 與 model 命名衝突

2010 Oct 05 未分類

用 CodeIgniter 常會遇到一個問題

有個Controller叫做 News

有個Model也叫做 News

實在是不知道怎麼改才好



................

在網路上找到一篇文章在講這個問題的解法

原始位置如下

http://www.dgpower.net/index.php/home/showonews/173

使用這個技巧要達到的目標:
一般來說,模型和控制器你都不會有相同的類名字。 讓我先創建一個取名為post的model。

class Post extends Model {

// ...

}
現在你就不能有一個像這樣的url:
http://www.mysite.com/post/display/13


這個原因是因為你也需要有一個名字為post的controller,如果創建了這樣的一個類的話將會引起致命錯誤。
但是使用了這個技巧一般,一切皆有可能。 那個url的控制器看起來是這樣的:
// application/controllers/post.php

class Post_controller extends Controller {

// ...

}
注意這個“__controller”後綴


技巧:
為了避免這個問題,通常大多數人都是添加'_model'後綴到model名字(例如命名Post_model)。
在所有的應用程序中Model對像都被創建和引用,所以在所有的model名字後面跟上'_model'有些無聊。
我認為最好的辦法就是在controller上來添加後綴,因為在代碼中controller的名字幾乎從來不會被引用。


首先我們需要繼承Router class。 創建這樣一個文件:"application/libraries/MY_Router.php"
class MY_Router extends CI_Router {
var $suffix = '_controller';

function MY_Router() {
parent::CI_Router();
}

function set_class($class) {
$this->class = $class . $this->suffix;
}

function controller_name() {

if (strstr($this->class, $this->suffix)) {
return str_replace($this->suffix, '', $this->class);
}
else {
return $this->class;
}

}
}
現在編輯"system/codeigniter/CodeIgniter.php"第153行
if ( ! file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT))
然後第158行
include(APPPATH.'controllers/'.$RTR->fetch_directory().$RTR->controller_name().EXT);
然後編輯"system/libraries/Profiler.php"的第323行


$output .= "<div style="color:#995300;font-weight:normal;padding:4px 0 4px 0">".$this->CI->router->controller_name()."/".$ this->CI->router->fetch_method()."</div>";

大功告成。 使用這個技巧一定需要記住的是要把'_controller'後綴放到你的controller的類的名字後面,不是放在你的控制器文件名中。

  • 分享此文章
0則留言

相關文章

負面能量積蓄

[歐付寶] 串電子發票

日幣破底 你還在猜底嘛? 換日幣的迷思

精鍊的樂趣

只要是奴隸的心態 就一輩子是奴隸

最近...

關於路老闆

推薦連結

  • Alice 你的理財陪跑教練
  • 羅鈞鴻/小虎老師
  • 徐慧玲Lynn
  • 寶寶牙醫 沈醫師
  • 保險資訊懶人包
  • 你的好感度教練
  • 天下為暢

聯絡我們

  • Email: louis@boss-louis.tw
  • 營業時間: 09:00~18:00
  • 聯絡電話: 02-77252950
  • 地址: 106 台北市大安區忠孝東路四段270號17樓
  • 隱私權政策
COPYRIGHT ©路老闆個人品牌網站 All rights reserved | Powered by 路老闆