9

I'm building my first CodeIgniter application and I need to make URLs like follows:

controllername/{uf}/{city}

Example: /rj/rio-de-janeiro This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')

Another URL possible is:

controllername/{uf}/{page}

Example: /rj/3 This example should give me 2 parameters: $uf ('rj') and $page (3)

In other words, the parameters "city" and "page" are optionals. I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'. But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).

4

3 に答える 3

16

私は正しい結果を見つけました:

$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';

Index メソッド (「ControllerName」内) は次のようになります。

public function Index($uf = '', $slug = '', $pag = 0)
{
    // some code...

    if (intval($pag) > 0)
    {
        // pagination
    }

    if (!empty($slug))
    {
        // slug manipulation
    }
}

それが誰かを助けることを願っています。皆さん、ありがとうございました。

于 2013-09-24T05:12:17.583 に答える
1
public function my_test_function($not_optional_param, $optional_param = NULL)
  { 
   //do your stuff here
  }

これを試しましたか?

于 2013-09-24T05:04:14.897 に答える
0

たとえば、次のような URI があるとします。

  1. example.com/index.php/mycontroller/myfunction/hello/world
  2. example.com/index.php/mycontroller/myfunction/hello

メソッドには URI セグメント 3 と 4 (「hello」と「world」) が渡されます。

class MyController extends CI_Controller {

public function myFunction($notOptional, $optional = NULL)
{
    echo $notOptional; // will return 'hello'.
    echo $optional; // will return 'world' using the 1st URI and 'NULL' using the 2nd.
}

}

参考:https ://codeigniter.com/user_guide/general/controllers.html

于 2015-10-01T04:35:51.360 に答える