我正在尝试使用自己的mvc构建一个类似http://example.com/username的网址,我使用前端控制器
<?php
namespace Core;
use Core\KliknklopException;
use Core\Config;
class Controller
{
const DEFAULT_CONTROLLER = "\\Controllers\\IndexController";
const DEFAULT_ACTION = "indexAction";
protected static $controller = self::DEFAULT_CONTROLLER;
protected static $action = self::DEFAULT_ACTION;
protected static $params = array();
public static function init(array $options = array()) {
if (empty($options)) {
self::parseUri();
}
else {
if (!empty($options["controller"])) {
self::$setController($options["controller"]);
}
if (!empty($options["action"])) {
self::$setAction($options["action"]);
}
if (!empty($options["params"])) {
self::$setParams($options["params"]);
}
}
}
protected static function parseUri() {
$path = trim(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/");
$path = preg_replace('[^a-zA-Z0-9/]', "", $path);
$basePath = Config::applicationConfig()['baseController'];
if (strpos($path, $basePath) === 0) {
$path = substr($path, strlen($basePath));
}
@list($controller, $action, $params) = explode("/", $path, 3);
if (!empty($controller)) {
self::setController($controller);
}
if (!empty($action)) {
self::setAction($action);
}
if (!empty($params)) {
self::setParams(explode("/", $params));
}
}
public static function setController($controller) {
$controller = "\\Controllers\\".ucfirst(strtolower($controller)) . "Controller";
if (!class_exists($controller)) {
throw new KliknklopException ("The action controller '$controller' has not been defined.");
}
self::$controller = $controller;
return self::$controller;
}
public static function setAction($action) {
if (!method_exists(self::$controller, $action . "Action")) {
throw new KliknklopException ("The controller action '$action'Action has been not defined.");
exit();
}
self::$action = $action. "Action";
return self::$action;
}
public static function setParams(array $params) {
self::$params = $params;
return self::$action;
}
public static function run() {
call_user_func_array(array(new self::$controller, self::$action), self::$params);
}
}
然后是控制器,我这样创建:
<?php
namespace Controllers;
class ProfileController {
public function __construct()
{
}
public function userAction($name_user) {
echo "hello {$name_user}";
}
}
我可以访问网址http://example.com/profile/user/panji控制器,如何创建像http://example.com/panji这样的网址,我是否必须使用htaccess或使用路由?请帮我。感谢
问候。