URL routing with codeigniter

I have a controller named search. Codeigniter works as follows, if the user types sitename.com/search, he enters the controller searchand launches the function index.

If the user then enters sitename.com/search/cars, the controller will look for a function carsin the controller search.

However, I want to have a generic function called lookup () that takes a second parameter in the URL string.

For example: sitename.com/search/ electronics [electronics returned] sitename.com/search/ cheese [cheese returned]

He then searches the database using the keyword if he finds a match that loads the page. In the case of machines, this will be sitename.com/search/cars, if there is no match, then it will be redirected to sitename.com/search/error.

Is it possible to change my controller to handle requests like this? Without indicating all possible routes?

$route['Cars'] = 'sitename.com/search/Cars';  
$route['Cheese'] = 'sitename.com/search/Cheese';  
$route['Electronics'] = 'sitename.com/search/Electronics';  

Search Controller:

    <?php
    class Search extends CI_Controller {


     public function __construct()
           {
                parent::__construct();

        $this->load->helper('url');

//parse URL: run lookup() function then redirect to page if valid return


           }


        public function index()
        {
        //check for url string to see what set or collection to load:

        }

       public function lookup()
       {

       }


    }
    ?>
0
source share
1 answer

on my way

$route['search/(:any)'] = "search/index/$1";

in the controller

        public function index($value)
    {
        //$value = $1

    }
+1
source

Source: https://habr.com/ru/post/1531565/


All Articles