问题
I'm Planning to make a project in codeigniter 3.0.3 and I want to use routing like below.
1) . www.mydomain.com/categoryNamehere
2) . www.mydomain.com/postNameHere
I have a separate table in my database to keep category names with their unique id's.
What I want is when a user click on a link like www.mydomain.com/xxxxx
1.first check on category table (xxxxx)
2. if no match send it (xxxxx) to post controller.
How can I implement this on Codeigniter 3.0.3 ?
I tried to access my models in config / routing.php and also I tried to execute mysql codes (active records) directly in routing page.
回答1:
To implement the proposed url structure, we must create one central dispatcher that would
- Analyze the requested URL.
- Would query a database to find and display the category.
- If no category found it would try to find and display the text post.
Sounds like the job for a controller. But how do we make a controller that responds to every request? With the help of wildcard routing!
application/config/routes.php
$route['.*'] = 'default_controller';
Now every request, regardless of URI, will be routed to Default_controller.php
.
But how do we write controller without knowing what method will be called? There is a way: the built-in in controller service method _remap
.
From the docs:
If your controller contains a method named _remap(), it will always get called regardless of what your URI contains.
So I've let myself fantasize and create a concept Default_controller for you:
application/controllers/Default_controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Default_controller extends CI_Controller {
// Pseudocode ensues
public function _remap()
{
// www.mydomain.com/(someTextHere)
$slug = $this->uri->segment(1);
$result = $this->load_data($slug);
echo $result;
}
private function load_data($slug)
{
// Trying to find a category
$category = $this->category_model->find($slug);
if($category !== false)
{
// Presumably loads view into buffer
// and returns it to the calling method
return $this->load_category($category);
}
Trying to find post
$post = $this->post_model->find($slug);
if($post !== false)
{
return $this->load_post($post);
}
// Neither category nor post found
show_404();
}
private function load_category($category)
{
// http://www.codeigniter.com/user_guide/general/views.html#returning-views-as-data
return $this->load->view("category", array("category" => $category), true);
}
}
Note: tested this answer on the freshly downloaded Codeigniter 3.0.3
来源:https://stackoverflow.com/questions/34229664/codeigniter-access-models-and-database-on-routing