PHP创建一个字符串模板,以便稍后注入字符串

时间:2015-07-12 13:56:34

标签: php

我正在创建一个字符串数组,这些字符串代表URI的模板,我后者想要使用不同的ID,我使用"%id"作为占位符

$template = array()
$template[] = "/campaigns/%id/";
$template[] = "/campaigns/%id/pictures";
$template[] = "/campaigns/%id/likes";

现在我还设置了一个可选ID数组:

$ids = array("123","456","789");

我有一个函数可以检查给定的URI是否有效。 此函数将接收URI,然后根据模板和我定义的ID将其与所有有效URI进行比较:

public function isUriAllowed($uri){
    $allowedUris = $this->getTemplateUris();
    foreach($this->ids as $id)
    {
        foreach($allowedUris as $allowedUri)
        {
            $allowedUri = str_replace($this->idPlaceHolder,$id,$allowedUri);
            if (strcmp($allowedUri,$uri) == 0)
                return true;
        }
    }
    return false;
}

我有一种直觉,有一种更优雅的方式来实现我想要做的事情,但我不知道该怎么做。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用此代码检查网址:

$test_url = '/campaigns/123/pictures';
$ids_availables = array("123","456","789");

$valid = preg_match('/\/campaigns\/('.implode('|', $ids_availables).')\/(pictures|likes)?/', $test_url, $matches);
/* print (boolean) if $test_url is valid */
var_dump($valid);
/* if is a valid url, $matches is an array that contains campaing_id and pictures/likes values */
var_dump($matches);

编辑:抱歉,我已经编辑过正确的sintaxis错误。

答案 1 :(得分:0)

让我猜一下,你正在尝试创建一种路由器??,让我分享你很久以前做过的路由器。

class Router {
  private $request_uri;
  private $routes;
  private static $instance = false;

  const DEFAULT_CONTROLLER = "MyController";
  const DEFAULT_ACTION = "myAction";

  public static function get_instance() {
    if(!self::$instance) {
      $class = get_called_class();
      self::$instance = new $class();
    }
    return self::$instance;
  }

  protected function __construct() {
    list($this->request_uri) = explode('?', $_SERVER['REQUEST_URI']);
  }

  public function set_route($route, $target = [], $condition = []) {
    $url_regex = preg_replace_callback('@:[\w]+@', function($matches) use ($condition) {
      $res = '([a-zA-Z0-9_\+\-%]+)';
      $key = str_replace(':', '', $matches[0]);
      if(array_key_exists($key, $condition)) $res = '('.$condition[$key].')';
      return $res;
    }, $route);
    preg_match_all('@:([\w]+)@', $route, $keys, PREG_PATTERN_ORDER);
    $this->routes[$route] = ['regex' => $url_regex .'/?', 'target' => $target, 'keys' => $keys[0]];
  }

  public function run() {
    $params = [];
    foreach($this->routes as $v) {
      if(preg_match('@^'.$v['regex'].'$@', $this->request_uri, $values)) {
        if(isset($v['target']['controller'])) $controller = $v['target']['controller'];
        if(isset($v['target']['action'])) $action =  $v['target']['action'];
        for($i = count($values) -1; $i--;) {
          $params[substr($v['keys'][$i], 1)] = $values[$i +1];
        }
        break;
      }
    }

    $controller = isset($controller) ? $controller : self::DEFAULT_CONTROLLER;
    $action = isset($action) ? $action : self::DEFAULT_ACTION;
    $redirect = new $controller();
    $redirect->{$action}(array_merge($params, $_GET, $_POST, $_COOKIE));
  }
}

如何使用它:

require_once 'Router.php';

$router = Router::get_instance();
$router->set_route("/");
$router->set_route("/nocontroller/noaction", ['controller' => 'NoController']);
$router->set_route("/nocontroller/nocontroller", ['action' => 'without']);
$router->set_route("/another/echoes/:param", ['controller' => 'Another', 'action' => 'echoes'], ['param' => '[a-z]{3}']);
$router->set_route("/another/echoes/:param/:id", ['controller' => 'Another', 'action' => 'dump'], ['param' => '[a-z]{3}', 'id' => '[\d]{1,8}']);
$router->set_route("/another/echoes/:param/some/:id", ['controller' => 'Another', 'action' => 'dump'], ['param' => '[a-z]{3}', 'id' => '[\d]{1,8}']);
$router->set_route("/another/echoes/:param/some/:id/:more", ['controller' => 'Another', 'action' => 'dump'], ['param' => '[a-z]{3}', 'id' => '[\d]{1,8}']);
$router->run();

好的,你需要使用一个自动加载器...如果你需要它只需要它:p,或者jsut为你将要使用的每个控制器提出要求。

如果不是这样,我道歉。毕竟,你的答案也在我的代码中。享受它!!

相关问题