【opencart3源码分析】操作类action.php

<?php
/**
 * @package        OpenCart
 * @author        Daniel Kerr
 * @copyright    Copyright (c) 2005 - 2017, OpenCart, Ltd. (https://www.opencart.com/)
 * @license        https://opensource.org/licenses/GPL-3.0
 * @link        https://www.opencart.com
 */

/**
 * 操作类
 */
class Action {
    // 操作id
	private $id;
	// 路由
	private $route;
	// 默认操作方法index
	private $method = 'index';

	/**
	 * 构造方法
	 * @param    string $route
	 */
	public function __construct($route) {
		$this->id = $route;

		$parts = explode('/', preg_replace('/[^a-zA-Z0-9_\/]/', '', (string)$route));

		// Break apart the route
		while ($parts) {
			$file = DIR_APPLICATION . 'controller/' . implode('/', $parts) . '.php';

			if (is_file($file)) {
				$this->route = implode('/', $parts);

				break;
			} else {
				$this->method = array_pop($parts);
			}
		}
	}

	/**
	 *
	 *
	 * @return    string
	 *
	 */
	public function getId() {
		return $this->id;
	}

	/**
	 *
	 * 执行
	 * @param    object $registry
	 * @param    array $args
	 */
	public function execute($registry, array $args = array()) {
		// 禁止调用魔术方法
		if (substr($this->method, 0, 2) == '__') {
			return new \Exception('Error: Calls to magic methods are not allowed!');
		}

		$file = DIR_APPLICATION . 'controller/' . $this->route . '.php';
		$class = 'Controller' . preg_replace('/[^a-zA-Z0-9]/', '', $this->route);

		// 初始化类
		if (is_file($file)) {
			include_once($file);

			$controller = new $class($registry);
		} else {
			return new \Exception('Error: Could not call ' . $this->route . '/' . $this->method . '!');
		}

		// 实例化一个反射类
		$reflection = new ReflectionClass($class);
        // 判断类是否存在特定的方法和参数个数是否满足要求
		if ($reflection->hasMethod($this->method) && $reflection->getMethod($this->method)->getNumberOfRequiredParameters() <= count($args)) {
			return call_user_func_array(array($controller, $this->method), $args);
		} else {
			return new \Exception('Error: Could not call ' . $this->route . '/' . $this->method . '!');
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/81351296
今日推荐