|
前言
原本以為最終會用 Laravel 來開發了,無奈昨日會議結束又有了新的政策,因為某些考量決定再度切回OpenCart。無用洪只是個小小工程助理,月薪扣除健保勞保不到三萬元,身分地位卑微至極,也只能默默接受了。今天就來和大家分享 OpenCart 的首日鑽研成果。( 安裝的部份就跳過了,這邊有介紹過了)
OpenCart 採用 MVC 模式
這意思是說,入口八成就是那個index.php了。index.php 一行一行看懂基本上就大概能知道 OpenCart 大概的運作邏輯了。Let's Go~。
宣告一個常數,該常數表示目前的OpenCart版本。
- <?php
- // Version
- define('VERSION', '1.5.2.1');
複製代碼
引入 config.php,該檔案主要為一些路徑常數和database相關的常數。
- <?php
- //...
- // Configuration
- require_once('config.php');
複製代碼
判斷 DIR_APPLICATION 是否有宣告,若沒有則導向安裝頁。
- <?php
- // ...
- // Install
- if (!defined('DIR_APPLICATION')) {
- header('Location: install/index.php');
- exit;
- }
複製代碼
引入 startup.php,該檔案包含了各種對環境的初始化設定,以及引入一些必要的類別。
- <?php
- // ...
- // Startup
- require_once(DIR_SYSTEM . 'startup.php');
複製代碼
引入一些必要類別,我是不清楚為什們不把它們放在 startup.php裡。
- <?php
- //...
- // Application Classes
- require_once(DIR_SYSTEM . 'library/customer.php');
- require_once(DIR_SYSTEM . 'library/affiliate.php');
- require_once(DIR_SYSTEM . 'library/currency.php');
- require_once(DIR_SYSTEM . 'library/tax.php');
- require_once(DIR_SYSTEM . 'library/weight.php');
- require_once(DIR_SYSTEM . 'library/length.php');
- require_once(DIR_SYSTEM . 'library/cart.php');
複製代碼
新增一個 Registry 實體,這個物件可以說貫穿整個 OpenCart,它的任務就是把各種必要物件註冊進來。
- <?php
- //...
- // Registry
- $registry = new Registry();
複製代碼
註冊 config 物件。
- <?php
- //...
- // Config
- $config = new Config();
- $registry->set('config', $config);
複製代碼
註冊 DB 物件,DB 的建構子會去 新增一個 MySQL 實體, MySQL 實體的建構子會建立一個資料庫連結。
- <?php
- //...
- // Database
- $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
- $registry->set('db', $db);
複製代碼
判斷有無分店,沒有個話 $config會設定 config_store_id 為 0。
- <?php
- // Store
- if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
- $store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
- } else {
- $store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
- }
- if ($store_query->num_rows) {
- $config->set('config_store_id', $store_query->row['store_id']);
- } else {
- $config->set('config_store_id', 0);
- }
複製代碼
一些類別和設定的引入,不是非常清楚用途,但不影響我們的探索。
- <?php
- // ...
- // Settings
- $query = $db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0' OR store_id = '" . (int)$config->get('config_store_id') . "' ORDER BY store_id ASC");
- foreach ($query->rows as $setting) {
- if (!$setting['serialized']) {
- $config->set($setting['key'], $setting['value']);
- } else {
- $config->set($setting['key'], unserialize($setting['value']));
- }
- }
- if (!$store_query->num_rows) {
- $config->set('config_url', HTTP_SERVER);
- $config->set('config_ssl', HTTPS_SERVER);
- }
- // Url
- $url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') : $config->get('config_url'));
- $registry->set('url', $url);
- // Log
- $log = new Log($config->get('config_error_filename'));
- $registry->set('log', $log);
複製代碼
以下這段這樣寫不是很妥當,違反了某些撰寫原則。隨便了,總之這段就是定義一個OpenCart 自己的錯誤處理器。
- <?php
- // ...
- function error_handler($errno, $errstr, $errfile, $errline) {
- global $log, $config;
-
- switch ($errno) {
- case E_NOTICE:
- case E_USER_NOTICE:
- $error = 'Notice';
- break;
- case E_WARNING:
- case E_USER_WARNING:
- $error = 'Warning';
- break;
- case E_ERROR:
- case E_USER_ERROR:
- $error = 'Fatal Error';
- break;
- default:
- $error = 'Unknown';
- break;
- }
-
- if ($config->get('config_error_display')) {
- echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
- }
-
- if ($config->get('config_error_log')) {
- $log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
- }
- return true;
- }
-
- // Error Handler
- set_error_handler('error_handler');
複製代碼
將 Request 和 Response 物件註冊,至於這兩個物件在做什們就不詳加介紹了,基本上就和一般 framework 很像,但是陽春很多。
- <?php
- //...
- // Request
- $request = new Request();
- $registry->set('request', $request);
-
- // Response
- $response = new Response();
- $response->addHeader('Content-Type: text/html; charset=utf-8');
- $response->setCompression($config->get('config_compression'));
- $registry->set('response', $response);
複製代碼
cache類別提供了一些對cache 檔案的操作方法,也是頗陽春,session 物件 則是在建構子會做一些關於 Session 的設定。
- <?php
- //...
- // Cache
- $cache = new Cache();
- $registry->set('cache', $cache);
- // Session
- $session = new Session();
- $registry->set('session', $session);
複製代碼
檢測環境載入的語言,並讀取對應的語言檔案。
- <?php
- //...
- // Language Detection
- $languages = array();
- $query = $db->query("SELECT * FROM " . DB_PREFIX . "language WHERE status = '1'");
- foreach ($query->rows as $result) {
- $languages[$result['code']] = $result;
- }
- $detect = '';
- if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
- $browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
-
- foreach ($browser_languages as $browser_language) {
- foreach ($languages as $key => $value) {
- if ($value['status']) {
- $locale = explode(',', $value['locale']);
- if (in_array($browser_language, $locale)) {
- $detect = $key;
- }
- }
- }
- }
- }
- if (isset($session->data['language']) && array_key_exists($session->data['language'], $languages) && $languages[$session->data['language']]['status']) {
- $code = $session->data['language'];
- } elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages) && $languages[$request->cookie['language']]['status']) {
- $code = $request->cookie['language'];
- } elseif ($detect) {
- $code = $detect;
- } else {
- $code = $config->get('config_language');
- }
- if (!isset($session->data['language']) || $session->data['language'] != $code) {
- $session->data['language'] = $code;
- }
- if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
- setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
- }
- $config->set('config_language_id', $languages[$code]['language_id']);
- $config->set('config_language', $languages[$code]['code']);
- // Language
- $language = new Language($languages[$code]['directory']);
- $language->load($languages[$code]['filename']);
- $registry->set('language', $language);
複製代碼
一些商店設定相關物件的初始化,就不一個一個講了,都很簡單。
- <?php
- //...
- // Document
- $registry->set('document', new Document());
- // Customer
- $registry->set('customer', new Customer($registry));
- // Affiliate
- $registry->set('affiliate', new Affiliate($registry));
- if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
- setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
- }
-
- // Currency
- $registry->set('currency', new Currency($registry));
- // Tax
- $registry->set('tax', new Tax($registry));
- // Weight
- $registry->set('weight', new Weight($registry));
- // Length
- $registry->set('length', new Length($registry));
- // Cart
- $registry->set('cart', new Cart($registry));
- // Encryption
- $registry->set('encryption', new Encryption($config->get('config_encryption')));
複製代碼
再來是比較需要花時間分析的部份:
index.php
- <?php
- //...
- // Front Controller
- $controller = new Front($registry);
- // Maintenance Mode
- $controller->addPreAction(new Action('common/maintenance'));
- // SEO URL's
- $controller->addPreAction(new Action('common/seo_url'));
-
- // Router
- if (isset($request->get['route'])) {
- $action = new Action($request->get['route']);
- } else {
- $action = new Action('common/home');
- }
- // Dispatch
- $controller->dispatch($action, new Action('error/not_found'));
- // Output
- $response->output();
複製代碼
這段程式碼流程如下:
1.先新增一個 Front 實體 $controller,然後新增兩個 Action 實體並用 $controller 的addPreAction() 方法將它們儲存起來。
2.接著再根據現在的URI 新增第三個 Action 實體 $action。
3.執行 $controller 的 dispatch()方法,將$action傳入當做第一個變數。
這邊看一下 Front 類別的程式碼:
front.php
- <?php
- final class Front {
- protected $registry;
- protected $pre_action = array();
- protected $error;
-
- public function __construct($registry) {
- $this->registry = $registry;
- }
-
- public function addPreAction($pre_action) {
- $this->pre_action[] = $pre_action;
- }
-
- public function dispatch($action, $error) {
- $this->error = $error;
-
- foreach ($this->pre_action as $pre_action) {
- $result = $this->execute($pre_action);
-
- if ($result) {
- $action = $result;
-
- break;
- }
- }
-
- while ($action) {
- $action = $this->execute($action);
- }
- }
-
- private function execute($action) {
- $file = $action->getFile();
- $class = $action->getClass();
- $method = $action->getMethod();
- $args = $action->getArgs();
- $action = '';
- if (file_exists($file)) {
- require_once($file);
- $controller = new $class($this->registry);
-
- if (is_callable(array($controller, $method))) {
- $action = call_user_func_array(array($controller, $method), $args);
- } else {
- $action = $this->error;
-
- $this->error = '';
- }
- } else {
- $action = $this->error;
-
- $this->error = '';
- }
-
- return $action;
- }
- }
複製代碼
4.我們可以看到, dispatch 會先迭代 pre_action 屬性並且透過 excute()方法執行。
5.excute() 會根據屬性引入需要的檔案並且執行對應的 controller 的方法。一般來說controller 在輸出到 view 這段會用到 ob_start() 做緩衝處理。
如果excute() 有回傳值,則 $action ( 傳入 dispatch 的實體 ) 會被回傳值取代,並且直接跳出迴圈。
如果 $action 存在,則將它傳入 excute() 方法執行。這邊這種寫法要特別小心,有機會造成無窮迴圈讓程式躺平。
整體來說不難懂,應該都能 trace 出來。就不介紹的太詳細了留給大家一點自己探索的樂趣。
小結:
OpenCart還是和Laravel 和 Symfony2 等檯面上正夯的框架架構有點落差,但還是不得不說,一個人能做到這樣真的很厲害了... |
|