【问题标题】:Codeigniter Routing - Using it too much?Codeigniter 路由 - 使用太多?
【发布时间】:2012-03-12 03:32:09
【问题描述】:

我是 Codeigniter 的新手,我正在尝试通过将旧站点转换为 CI 来适应它。

我无法理解的一件事是路由。如果我不想拥有像 /controller/method/id 这样的 url 结构,我必须在 routes.php 中将其更改为 $route['controller/(:num)'] = "controller/method/$1"; 之类的东西。对我来说似乎效率低下,我应该做点别的吗?

例如,在我的网站上,网址是 /game/4242 和 /player/SomeDude

【问题讨论】:

  • 什么对您有帮助?如果您不想全部手动编写,您的网址中必须包含一些逻辑。
  • 效率是什么意思? MVC 架构具有这种 URL 结构。在那之后,如果您不喜欢在您的地址上执行 MVC 结构,那么 CI 可以很容易地更改您的 URL。你还想要什么?

标签: php codeigniter url-routing


【解决方案1】:

好吧,路由是有效的 - 替代方案是 remapping your controllers。

让我们来看看这两种可能性。

一个想象的情况: 稍后,您希望允许您的用户在他们的个人资料上显示徽章/奖牌/成就/某些东西。

使用路由,可以这样实现:

$route['player/(:any)/(:any)'] = "player/show_$2/$1";
$route['player/(:any)'] = "player/show_profile/$1";

你的控制器可能看起来像这样:

class Player extends CI_Controller
{
  public function show_profile( $username )
  {
    // the profile info
  }

  public function show_badges( $username )
  {
    // the profiles badges
  }

  public function show_scores( $username )
  {
    // the profiles scores
  }
}

}

基本上,这允许您在控制器中简单地添加另一个方法,在该方法前加上 show_(如 public method show_friends( $username )),然后您可以通过转到 /player/SomeDude/friends立即访问它>

看看替代方案,重新映射您的控制器将允许您不使用路由,而是像这样编写一个控制器:

class Player extends CI_Controller
{

  public function _remap($username, $params = array())
  {
    if(empty($username))
      show_404();

    $this->user = $this->user_model->find($username);

    if(count($params) == 0)
      $method = 'index';
    else
      $method = $params[0];

    unset($params[0]); //No need to send the method along as a parameter

    $method = 'process_'.$method;
    if (method_exists($this, $method))
    {
      return call_user_func_array(array($this, $method), $params);
    }
    show_404();
  }

  public method process_index()
  {
    // the profile info
  }

  public method process_badges()
  {
    // the profiles badges
  }

  public method process_scores()
  {
    // the profiles scores
  }

}

就个人而言,我喜欢路由。我认为它是透明的,让我的控制器看起来更干净。

【讨论】:

  • 这就是我想知道的!只是想确保我以正确的方式做事。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
  • 2011-07-08
相关资源
最近更新 更多