这个问题来自于我创建的另一个问题,你可以在这里找到但是我改变了我的代码,所以现在它看起来像这样:
汽车控制器public function indexAction(){
$category = new Application_Model_CarMapper();
$gcat = $this->getRequest()->getPathInfo();
//get id
$id = $category->find_id_by_name($gcat);
$this->view->title = $category->get_sub_cat_select($id);
}
这是我在映射器中创建的一个新函数:
public function find_id_by_name($name){
$select = $this->getDbTable()->query("SELECT * FROM car_category WHERE category_name = '{$name}'");
$result = $select->fetchAll();
if(!$result) {
return;
}
return $result[0]['ID'];
}
我正在测试它的标题,但它似乎没有显示在所有。我希望它能显示特定类别的下拉菜单,例如
car-live。local/cars/Volvo -> "欢迎来到Volvo汽车搜索"
car-live。local/cars/BMW -> "欢迎来到BMW汽车搜索"
我知道这是不工作,因为我不得不拆分URL甚至更多,因为现在它是通过URL找到id,但我不确定如何做到这一点:s任何光你可以洒在这将是非常感激。谢谢。
[编辑]
新代码:public function indexAction(){
$category = new Application_Model_CarMapper();
$gcat = explode("/", $this->getRequest()->getPathInfo());
if(isset($gcat['category_name'])) {
$id = $category->find_id_by_name($gcat);
$this->view->title = $category->get_sub_cat_select($id);
}
}
我不确定我是否正确理解了你的问题,但从代码来看,你似乎有问题处理URL。那么,让我们来看这个例子:
car-live.local/car/Volvo
当你到达indexAction
时,你应该被/
爆炸。
这是返回一个数组与URL的所有组件,然后你采取最后一个在这种情况下将是Volvo
,并将其发送到您的find_id_by_name()
方法。
我通常处理这个问题的方法是:
- 获取第一个(在本例中为
car
)并将其"路由"到cars类,通过发送给构造函数和请求的其余部分; -
car
类构造函数然后采取URLVolvo
的下一部分和"路由"它一个适当的方法,如getVolvo()
或任何你需要的…
你可以把它路由到你需要的地方,但是要把处理URL的责任委托给适当的类。例子:
/cars/whatEverCar
=>应由car
类处理
/bike/whatEverBike
=>应由bike
类处理
希望对你有帮助。
编辑:
你的find_id_by_name()
方法可以有一些URL,如:
/car/find_id_by_name/Volvo
我解释得好吗?你可以取URL的一部分并直接调用方法…并发送URL的其余部分。
编辑2:代码示例…
下面的代码是一个很好的解决你的问题:
<?php
// Call this class as soon the site stars
class Router {
public function __construct() {
// In some really cool way get your full URL, for example I'm gonna use a string...
$fullURL = "example.com/Car/findCarById/Volvo";
array_shift($fullURL); // removes "example.com", obvious stuff...
$explodedUrl = explode("/", $fullURL);
$targetClass = $explodedUrl[0]; // Temporary store the target is "Car"
array_shift($fullURL); // Removes "Car", we don't need it anymore...
$target = new $targetClass($fullURL); // call the Car class responsible for handling all the "Car" related stuff!
}
}
class Car {
public function __construct($request) {
// $request is an array with "findCarById", "Volvo"
$targetMethod = $request[0]; // Temporary store the target is "findCarById"
array_shift($request);
$this->$targetMethod($request);
}
private function findCarById($parameter) {
// $parameter is an array with "Volvo"..
// Now to your query and other cool stuff with $parameter[0];
print "I'm the method findCarById() of the class Car called by the main router to find the ID for {$parameter}...";
}
}
?>
如果你需要在Car
类中添加更多的函数,只需添加另一个方法,然后用他的名字在URL上调用它,就像我对findCarById()
所做的那样。
警告:此代码可能有小错误,它是在记事本上编写的,未经过测试。