路线类无法正常工作

时间:2016-01-31 09:58:53

标签: php wrapper

我正在重写以前用CodeIgniter框架编写的应用程序,我的客户希望有一个独立的应用程序和纯PHP代码。无论如何不要告诉我 不要重新发明轮子 ,因为我已经知道我的客户端是错的。我们来解决这个问题 我正在寻找一个简单的Route类,它允许我从任何位置调用任何文件。我找到了这个简单而强大的类this is the repository
我已经在我的项目中实现了它,将route.php文件复制到索引位置并更改我的.htaccess,如文档所述。而不是全部,这是我的项目的结构:

/ PUBLIC_HTML
   / application 
           / controllers
               /backend.php
               /user.php
           / helpers
           / models
           / views
               /backend
                   /backend.php
                   /calendar.php
               /user
                   /users.php
                   /panel.php
   / assets
           / files used by frontend...
   / system
           / configuration
           / constant
   / .htaccess
   / index.php
   / route.php

当从index.php启动applicationi时,包含配置文件以建立与数据库的连接。在同一个configuration文件中,我导入了route.php。现在我的index.php页面很简单,就像这样:

// Check if the session is set

if(isset($_SESSION['user_info']['id_roles']))
{
    switch($_SESSION['user_info']['id_roles'])
    {
        case 1:         //Admin
            $route->add('/application/controllers/backend', 'index');
            $route->submit();
            break;
        case 2:         //Provider
            $route->add('/application/controllers/backend');
            $route->submit();
            break;
        case 3:         //Customer
            $route->add('/application/controllers/appointments');
            $route->submit();
            break;
    }
}
else
{
    // Session isn't set, so I redirect user to login page

    header('Location: application/views/user/login.php');
    exit; // stop
}

所以如果设置了session,我会将用户类型重定向到正确的位置,如果没有设置,则显示登录页面。 login页面简单地为会话变量增值,如果响应成功,则用户再次重定向到索引页面。
现在的问题是,例如,当管理员被记录时(case 1),route类没有对$uri进行定值,例如:

public function submit()
{
    $uri = isset($_REQUEST['uri']) ? $_REQUEST['uri'] : '/';
    $uri = trim($uri, $this->_trim);

    $replacementValues = array();

    // Iterate on the list of URI

    foreach($this->_listUri as $listKey => $listUri)
    {
        // Looking for a match..

        if(preg_match("#^$listUri$#", $uri))
        {
            // Replace the values

            $realUri = explode('/', $uri);
            $fakeUri = explode('/', $listUri);

            // Get value with .+ with real URI value

            foreach($fakeUri as $key => $value)
            {
                if ($value == '.+')
                {
                    $replacementValues[] = $realUri[$key];
                }
            }

            // Pass array arguments..

            call_user_func_array($this->_listCall[$listKey], $replacementValues);
        }
    }
}

check the full class here

$uri变量应该使用服务器的当前uri进行定值,但我尝试使用var_dump并获得一个空值。然后永远不会调用匹配条件,并且正确的文件不是没有显示出来。我不知道为什么,我只是想明白为什么它不起作用,我可能做错了什么,有人可以帮我理解?
完成管理员重定向的示例后,我只想显示backend.php中包含的内容,该内容应从route加载。

<?php

  session_start();

  class Backend
  {
    // Construct of class

    public function __construct()
    {

    }

    // Display the main backend page

    public function index($appointment_hash = '')
    {
       $_SESSION['user_info']['hash'] = $appointment_hash;
       $_SESSION['user_info']['dest_url'] = SystemConfiguration::$base_url . "backend";
       // some content..
    }

    ...

所以你怎么看,我只想在调用index时调用backend控制器的->add()函数来添加要调用的控制器的url,{{1执行操作。
我做错了什么?

更新 - 路由器请求任务

首先我更新了我的应用程序的堆栈。 我想在这一点上,最好询问您的专家建议,告诉我哪些OpenSource路由器允许我实现这些任务:

1。导入控制器

导入名为->submit()的文件夹中包含的所有控制器。一旦你导入我将简单地调用路由器的实例,并调用加载的控制器的特定功能。例如:

controllers

其中$router->backend->index(); 它表示名为index();的控制器的功能。 这必须在我的整个申请中完成。此外,我还要确保我们也可以通过URL启动该功能,特别是,如果我插入此URL:

backend

我可以简单地引用url来调用相同的函数。

2。请求ajax 交付我的路由器必须能够从javascript运行ajax请求,特别是如果我使用此代码:

localhost/application/controllers/backend/index

我想调用用户函数$('#login-form').submit(function(event) { var postUrl = GlobalVariables.baseUrl + 'user/ajax_check_login'; var postData = { 'username': $('#username').val(), 'password': $('#password').val() }; $('.alert').addClass('hidden'); $.post(postUrl, postData, function(response) { 。 包含在控制器ajax_check_login中,想象user,是什么......我们怎么能想到基本应用程序的URL明显可以变化。 请注意,我的Controller函数返回json格式。

第3。加载视图

在我的应用程序中有一个视图,它保存在GlobalVariables.baseUrl中,但包含html文件,一个视图示例(以前用CodeIgniter编写),你发现here。 我希望能够调用视图并显示新用户html标记。我还需要在同一时刻调用更多视图,例如有时我将身体划分为:

.php

为了简化对header, body, footer 在视图中引用的内容的理解,由于视图是由控制器方法“加载”的,因此视图仍然在与该方法相同的范围内运行,这意味着{{1}根据加载它的类,可以有不同的上下文。

例如:

$this

在此示例控制器中加载的任何视图文件中,$this专门指Controller1类,它也可以访问class Controller1 extends CI_Controller {} 公共和受保护的属性/方法(如Loader或Input类,被分配给CI_Controller的加载和输入属性,因为它扩展该类。

控制器仍然只是普通的旧PHP类。如果我这样做:

$this

...如果我们在这些控制器中的任何一个的任何方法中加载相同的视图文件,则在该视图文件中使用CI_Controller将返回不同的值。 但现在这并不重要,我只想尽可能清楚。 我开始计算并失去我的所有代表,但我真的希望得到这方面的帮助并学习。

1 个答案:

答案 0 :(得分:3)

您需要查看路由器提供的index.php作为示例。您将了解如何设置路线:

  • 你总是要有两个参数:1。uri,2。function
  • 根据示例,函数必须不是函数名'index',而是函数体function(){...}。也许参考也可以。
  • 路由恕我直言不应该依赖会话(尽管可能是,但这不是通常的做法)
  • 而不是$router->backend->index();,我会在文件末尾有一个共同的代码块,因此您不必多次复制和粘贴代码。

我会以你的方式向你展示后端,然后通过约会你怎么能把它变成一般的。所以你应该让你的路线像:

<?php
session_start();
include 'route.php';
$phpClass = false;
$view = false;
$func = false;
$route = new Route();
if(isset($_SESSION['user_info']) && isset($_SESSION['user_info']['id_roles'])) {
  $route->add('/application/controllers/backend', function(){
    echo 'You are now at backend page, and the role is ';
    switch($_SESSION['user_info']['id_roles']) {
      case 1: echo 'Admin'; break;
      case 2: echo 'Provider'; break;
      case 3: echo 'Customer'; break;
    }
    include 'backend.php';
    $backend = new Backend();
    $backend->index(/* I don't know what 'hash' could be */);
  });

  // more general case:
  $route->add('/application/controllers/appointments', function(){
    // we only set the global $phpClass variable, and the rest is common, see below
    global $phpClass, $func;
    $phpClass = 'Appointements';
    $func = 'index'; // default is index, if it wasn't given on the url
  });
  $route->add('/application/controllers/appointments/add', function(){
    // we only set the global $phpClass variable, and the rest is common, see below
    global $phpClass, $func;
    $phpClass = 'Appointements';
    $func = 'add';
  });
  $route->add('/application/controllers/appointments/delete', function(){
    // we only set the global $phpClass variable, and the rest is common, see below
    global $phpClass, $func;
    $phpClass = 'Appointements';
    $func = 'delete';
  });
  $route->add('/application/controllers/foo', function(){
    global $phpClass;
    $phpClass = 'Foo';
  });
  $route->add('/application/controllers/bar', function(){
    global $phpClass;
    $phpClass = 'Bar';
  });

  $route->add('/application/views/bar', function(){
    global $phpClass, $view;
    $phpClass = 'View';
    $func = 'show';
    $view = 'bar.php';
  });

  $route->submit();
} else {
  // Session isn't set, so I redirect user to login page
  header('Location: /application/views/user/login.php');
  exit; // stop
}

if ($phpClass === false || $func === false) {
  die("You have to have both controller and function un the url");
}

// if we got here it means we're in the common case

// include the necessary controller. If you want you can
// include all of them at the top of the php and remove this line
include 'application/controllers/' . strtolower($phpClass) . '.php';

$controller = new $phpClass();

// this is instead of `$router->backend->index();`:
$controller->$func(/*$hash*/);
// I don't know what '$hash' could be, maybe javascript could send it via ajax

?>

控制器/ view.php:

class View {
    public function show() {
        global $view;
        include 'application/views/' . $view;
    }

    // here you'll need to have all the things that any of
    // your views access as $this->bar :
    $config = new stdClass(...);
    $array = array();
    function get_lang() {global $lang; return $lang;}
    //...
}

controllers / user.php中的json响应示例:

class User {
    public function logged_in() {
        $username = isset($_SESSION) && isset($_SESSION['username']) ? $_SESSION['username'] : false;
        $response = array(
          'success' => $username !== false ? 'OK' : 'ERROR',
          'username' => $username
        );
        echo json_encode($response);
    }
}
相关问题