동적 인 탐색 메뉴가있는 웹 사이트가 있습니다. 나는 컨트롤러 (포르투갈어) 이름을 데이터베이스에 보관하고 영어로 번역합니다.CodeIgniter - 동적으로 경로 생성
런타임에 'route'배열에 영향을 미칠 수 있는지 알고 싶습니다. 그러면 해당 경로가 만들어지고 페이지가로드 될 때 캐시됩니다.
나는
동적 인 탐색 메뉴가있는 웹 사이트가 있습니다. 나는 컨트롤러 (포르투갈어) 이름을 데이터베이스에 보관하고 영어로 번역합니다.CodeIgniter - 동적으로 경로 생성
런타임에 'route'배열에 영향을 미칠 수 있는지 알고 싶습니다. 그러면 해당 경로가 만들어지고 페이지가로드 될 때 캐시됩니다.
나는
이 작업을 수행 할 수 있습니다 :
이 내부를 넣어
pdo_db_connect.php라는 이름의 config 디렉토리에 파일을 작성하고 그에 따라 변경 테이블 명명 된 경로
--
-- Table structure for table `Routes`
--
CREATE TABLE IF NOT EXISTS `Routes` (
`idRoutes` int(11) NOT NULL AUTO_INCREMENT,
`Order` int(11) NOT NULL,
`Url` varchar(250) NOT NULL,
`Url_Variable` varchar(20) NOT NULL,
`Class` text NOT NULL,
`Method` text NOT NULL,
`Variable` text NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idRoutes`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=67 ;
을 만듭니다.당신의 경로에 이제
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
function pdo_connect(){
try{
// Include database info
include 'database.php';
if(!isset($db)){
echo 'Database connection not available!';
exit;
}
$dbdriver = $db['default']['dbdriver'];//'mysql';
$hostname = $db['default']['hostname'];//'localhost';
$database = $db['default']['database'];//'config';
$username = $db['default']['username'];//'root';
$password = $db['default']['password'];//'password';
//to connect
$DB = new PDO($dbdriver.':host='.$hostname.'; dbname='.$database, $username, $password);
return $DB;
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
은 당신이 할 수있는 파일 : 지나치게 복잡하지
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
// Include our PDO Connection
include('application/config/pdo_db_connect.php');
class dynamic_route{
public $pdo_db = FALSE;
public function __construct(){
}
private function query_routes(){
try{
$routes_query = $this->pdo_db->query('SELECT * FROM Routes ORDER BY `Order` ASC');
if($routes_query){
$return_data = array();
foreach($routes_query as $row) {
$return_data[] = $row;
}
return $return_data;
}
}catch(PDOException $e) {
echo 'Please contact Admin: '.$e->getMessage();
}
}
private function filter_route_data($data){
$r_data = array();
foreach($data as $row){
$return_data = new stdClass;
if(empty($row['Url_Variable'])){
$return_data->url = $row['Url'];
}else{
$return_data->url = $row['Url'].'/'.$row['Url_Variable'];
}
if(empty($row['Method']) && empty($row['Variable'])){
$return_data->route = $row['Class'];
}elseif(!empty($row['Method']) && empty($row['Variable'])){
$return_data->route = $row['Class'].'/'.$row['Method'];
}elseif(!empty($row['Method']) && !empty($row['Variable'])){
$return_data->route = $row['Class'].'/'.$row['Method'].'/'.$row['Variable'];
}
$r_data[] = $return_data;
}
return $r_data;
}
public function get_routes(){
$route_data = $this->query_routes();
$return_data = $this->filter_route_data($route_data);
return $return_data;
}
}
$dynamic_route = new dynamic_route;
// Give dynamic route database connection
$dynamic_route->pdo_db = pdo_connect();
// Get the route data
$route_data = $dynamic_route->get_routes();
//Iterate over the routes
foreach($route_data as $row){
$route[$row->url] = $row->route;
}
예 여기 좀 걸릴 수 있습니다 도움을 위해, 내가 충분히 분명했다 덕분에 희망 :
이 경로의 파일이 기억 어레이가 들어있는 PHP 파일 일뿐입니다. 따라서 "해커"티셔츠를 원한다면 조금 더러운 것을 쉽게 할 수 있습니다.
데이터베이스에 레코드를 만들고 저장하는 인터페이스가있는 CMS/응용 프로그램/Web-app/fridge-monitoring-system/것이 있습니까? 그런 다음 저장할 때마다이 내용을 application/cache/routes.php에 넣으십시오.
마지막으로 주요 routes.php에 캐시 된 버전이 포함되어 있으므로 잘하겠습니다.
다음이 필요합니다. 응용 프로그램/캐시 폴더에 "routes.php"라는 파일에 경로를 절약 할 수있는이 같은
한 컨트롤러 :
public function save_routes()
{
// this simply returns all the pages from my database
$routes = $this->Pages_model->get_all($this->siteid);
// write out the PHP array to the file with help from the file helper
if (!empty($routes)) {
// for every page in the database, get the route using the recursive function - _get_route()
foreach ($routes->result_array() as $route) {
$data[] = '$route["' . $this->_get_route($route['pageid']) . '"] = "' . "pages/index/{$route['pageid']}" . '";';
}
$output = "<?php if (! defined('BASEPATH')) exit('No direct script access allowed');\n";
$output .= implode("\n", $data);
$this->load->helper('file');
write_file(APPPATH . "cache/routes.php", $output);
}
}
여기 당신이 필요합니다 두 번째 기능입니다. 페이지를 처리하는이 사람과 일 개 이전에 뜻을 두 응용 프로그램 컨트롤러에 이동 :
// Credit to http://acairns.co.uk for this simple function he shared with me
// this will return our route based on the 'url' field of the database
// it will also check for parent pages for hierarchical urls
private function _get_route($id)
{
// get the page from the db using it's id
$page = $this->Pages_model->get_page($id);
// if this page has a parent, prefix it with the URL of the parent -- RECURSIVE
if ($page["parentid"] != 0)
$prefix = $this->_get_route($page["parentid"]) . "/" . $page['page_name'];
else
$prefix = $page['page_name'];
return $prefix;
}
이 라인을 따라 뭔가를해야 할 것이다 Pages_model에서
:
function get_page($pageid) {
$this->db->select('*')
->from('pages')
->where('pageid', $pageid);
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $row;
}
}
그리고이 :
function get_all($siteid) {
$this->db->select('*')
->from('pages')
->where('siteid', $siteid)
->order_by('rank');
;
$query = $this->db->get();
$row = $query->row_array();
$num = $query->num_rows();
if ($num < 1)
{
return NULL;
} else {
return $query;
}
}
페이지를 만들 때마다이 선을 실행해야하므로 모든 더러운 작업이 완료된 후에 컨트롤러 끝에 붙여 넣는 것이 좋습니다.
$this->save_routes();
이 모든 것이 함께 변경 될 때마다 지속적으로 업데이트되는 달콤한 경로 파일입니다.
뭔가를, 그것은 친화적 인 URL을 유지 :
routes.php의 내부 :
// Routes from the database
require_once (BASEPATH .'database/DB.php');
$db =& DB();
// slug will be something like
// 'this-is-a-post'
// 'this-is-another-post'
$sql = "SELECT id, slug FROM items";
$query = $db->query($sql);
$result = $query->result();
foreach($result as $row)
{
// first is if multiple pages
$route["$row->slug/(:num)"] = "item/index/$row->id";
$route["$row->slug"] = "item/index/$row->id";
}
을
기본 키로 'id'를 사용하고 '슬러그'는 고유 한 것으로 가정합니다.
컨트롤러 내부, 당신은에 의해 ID를 얻을 수 있습니다
$id = $this->uri->rsegment(3);
카일, 난 지금도 오랜 시간 동안 더 이상 PHP로 작업하고 있지 않다으로이를 테스트 할 수있는 방법이 없습니다. 이거 테스트 해봤 니? 당신이이 코드가 작동하는지 확신한다고 말하면, 정확히 물어 보는 것처럼 보이는 것처럼 당신의 답을 받아 들일 것입니다. –
예, 작동합니다. 사용하는 앱이 있습니다. – jphreak