简体   繁体   English

对Codeigniter中的“添加”和“编辑”使用相同的功能?

[英]Use same function for both 'add' and 'edit' in Codeigniter?

I want both these urls: 我想要这两个网址:

/admin/users/add / admin /用户/添加

and

/admin/users/3/edit / admin / users / 3 / edit

to point to edit($user_id = 0) function in my users controller. 指向我的用户控制器中的edit($user_id = 0)函数。 The number 3 in the second url has to be passed to the $user_id parameter. 第二个URL中的数字3必须传递给$user_id参数。

How can I do this in a smooth way? 如何顺利进行?

By setting up a route in application/config/routes.php: 通过在application / config / routes.php中设置路由

$route['admin/users/add'] = "users/edit";
$route['admin/users/(:num)/edit'] = "users/edit/$1";

If you want this to work for other controller too, you can do this: 如果您也希望它也适用于其他控制器,则可以执行以下操作:

$route['admin/(:any)/add'] = "$1/edit";
$route['admin/(:any)/(:num)/edit'] = "$1/edit/$2";

Or the same, using regular expressions: 或相同,使用正则表达式:

$route['admin/([a-z]+)/add'] = "$1/edit";
$route['admin/([a-z]+)/(\d+)/edit'] = "$1/edit/$2";

As an alternative to separate your logic. 作为分隔逻辑的替代方法。

I generally have two controllers that both speak to the same view. 我通常有两个控制器,它们都使用相同的视图。

admin/user/add
admin/user/edit/3

Both point to the view 两者都指向视图

admin/user_form.php

Which then access a save_user() method when the form has been posted. 发布表单后,该方法然后访问save_user()方法。

But as Mischa said, by setting up routes you can point pretty much any url to any method. 但是正如Mischa所说,通过设置路由,您几乎可以将任何URL指向任何方法。

Can you do this 你能做这个吗

public function users ($type, $id = null)
{
     if ($type === 'edit')
     {
           // do edit stuff
     }
     else
     {
           // ad add stuff
     }
 }

Sulotion: 抽提:

function _remap($method)
{
$param_offset = 2;

// No method, point to...
if (!method_exists($this, $method))
{
    if (is_numeric($method) || $method == 'add')
    {
        // Show single
        $param_offset = 1;
        $method = 'show';
    }
    else
    {
        // Index
        $param_offset = 1;
        $method = 'index';
    }
}

// Since all we get is $method, load up everything else in the URI
$params = array_slice($this->uri->rsegment_array(), $param_offset);

// Call the determined method with all params
call_user_func_array(array($this, $method), $params);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM