### router::createApp() — Bootstrap and Create the Application Source: https://context7.com/easysoft/zentaophp/llms.txt The static factory method that instantiates the framework. It sets up all path roots, loads config, initializes super-variable wrappers, starts the session, optionally connects to the database, and sets client language/theme/device. ```APIDOC ## router::createApp() ### Description Instantiates the zentaoPHP framework, setting up paths, configuration, session, and database connection. ### Method `static public function createApp(string $appName, string $appRoot, string $routerClass)` ### Parameters - **appName** (string) - The name of the application. - **appRoot** (string) - The root directory of the application. - **routerClass** (string) - The class name for the router. ### Request Example ```php loadCommon(); // Parse the incoming URL to determine module + method $app->parseRequest(); // Load and execute the resolved module/method $app->loadModule(); // Output, stripping any UTF-8 BOM echo helper::removeUTF8Bom(ob_get_clean()); ?> ``` ``` -------------------------------- ### Blog Module Controller Example Source: https://context7.com/easysoft/zentaophp/llms.txt Demonstrates a `blog` controller extending `control` (which extends `baseControl`). Includes methods for displaying paginated lists, creating articles, handling API requests, viewing a single article, and embedding other module outputs. ```php app->loadLang('common'); } // GET /blog/ — paginated list public function index($recTotal = 0, $recPerPage = 20, $pageID = 0) { $this->app->loadClass('pager'); $pager = new pager($recTotal, $recPerPage, $pageID); $this->view->title = $this->lang->blog->index; $this->view->articles = $this->blog->getList($pager); $this->view->pager = $pager; $this->display(); // renders module/blog/view/index.html.php } // POST /blog-create.html — create article public function create() { if(!empty($_POST)) { $blogID = $this->blog->create(); if(dao::isError()) die(js::error(dao::getError()) . js::locate('back')); die(js::locate(inlink('index'))); } $this->view->title = $this->lang->blog->add; $this->display(); } // Ajax-friendly response public function apiCreate() { $blogID = $this->blog->create(); // Sends JSON: {"result":"success","data":{"id":42}} or {"result":"fail","message":{...}} $this->send(array('result' => 'success', 'data' => array('id' => $blogID))); } // GET /blog-view-5.html public function view($id) { $this->view->article = $this->blog->getById($id); $this->display(); } // Embed another module's output inside this view public function dashboard() { $recentPosts = $this->fetch('blog', 'index', array('recPerPage' => 5)); $this->assign('recentPosts', $recentPosts); $this->display(); } } ``` -------------------------------- ### Blog Module Model Example Source: https://context7.com/easysoft/zentaophp/llms.txt Illustrates a `blogModel` extending `model` (which extends `baseModel`). Shows methods for fetching paginated lists, retrieving by ID, creating, updating, and loading sibling models for business logic and database interactions. ```php dao->select('*')->from('blog') ->orderBy('id desc') ->page($pager) ->fetchAll(); } // Fetch single record by ID public function getById($id) { return $this->dao->findById($id)->from('blog')->fetch(); } // Create — using fixer::input() to sanitize POST safely public function create() { $article = fixer::input('post') ->specialchars('title, content') ->add('date', date('Y-m-d H:i:s')) ->get(); $this->dao->insert('blog') ->data($article) ->autoCheck() ->batchCheck('title,content', 'notempty') ->exec(); if(dao::isError()) return false; return $this->dao->lastInsertID(); } // Update public function update($articleID) { $article = fixer::input('post')->specialchars('title, content')->get(); $this->dao->update('blog')->data($article)->where('id')->eq($articleID)->exec(); } // Load a sibling model public function getWithAuthor($id) { $this->loadModel('user'); // access as $this->user $article = $this->getById($id); $article->author = $this->user->getById($article->authorID); return $article; } } ``` -------------------------------- ### Configure zentaoPHP Framework Source: https://context7.com/easysoft/zentaophp/llms.txt Customize framework settings by overriding defaults in `config/my.php`. This example shows database connection, URL routing type, multi-language settings, and extension system configuration. Use `config->set()` for dot-notation assignment. ```php db->host = 'localhost'; $config->db->port = '3306'; $config->db->name = 'myapp'; $config->db->user = 'root'; $config->db->password = 'secret'; $config->installed = true; // URL routing: PATH_INFO (pretty URLs) or GET (?m=module&f=method) $config->requestType = 'PATH_INFO'; $config->requestFix = '-'; // URL separator: /blog-view-1.html // Enable multi-language support $config->framework->multiLanguage = true; $config->default->lang = 'en'; $config->langs['en'] = 'English'; $config->langs['zh-cn'] = '简体中文'; // Enable the extension system (0=off, 1=common ext, 2=per-site ext) $config->framework->extensionLevel = 1; // Use dot-notation to set nested config values at runtime $config->set('db.strictMode', false); // Equivalent to: $config->db->strictMode = false; ``` -------------------------------- ### Client Information Retrieval Source: https://context7.com/easysoft/zentaophp/llms.txt Get browser information, operating system, and remote IP address using `helper::getBrowser()`, `helper::getOS()`, and `helper::getRemoteIp()`. ```php 'chrome', 'version' => '120'] $os = helper::getOS(); // 'Windows 10' $ip = helper::getRemoteIp(); // '192.168.1.1' ``` -------------------------------- ### Checksum Generation Example Source: https://github.com/easysoft/zentaophp/blob/master/lib/purifier/standalone/HTMLPurifier/ConfigSchema/schema/URI.MungeSecretKey.txt This code demonstrates how a checksum is generated using SHA256 and a secret key. It's used to verify the integrity of URIs processed by HTML Purifier. ```php $checksum === hash_hmac("sha256", $url, $secret_key) ``` -------------------------------- ### Setting HTML.DefinitionID and Adding an Attribute Source: https://github.com/easysoft/zentaophp/blob/master/lib/purifier/standalone/HTMLPurifier/ConfigSchema/schema/HTML.DefinitionID.txt This example demonstrates how to set a custom DefinitionID and then use the advanced API to add an attribute to the HTML definition. This is necessary when your custom edits are not reflected in the standard configuration. ```php $config = HTMLPurifier_Config::createDefault(); $config->set('HTML', 'DefinitionID', '1'); $def = $config->getHTMLDefinition(); $def->addAttribute('a', 'tabindex', 'Number'); ``` -------------------------------- ### Safe Array/Object Access with zget Source: https://context7.com/easysoft/zentaophp/llms.txt Access array or object properties safely with `zget()`, providing a default value if the key or property does not exist. Useful for configuration and GET parameters. ```php db, 'host', 'localhost'); // Returns $config->db->host if set, else 'localhost' $item = zget($_GET, 'page', 1); ``` -------------------------------- ### Bootstrap zentaoPHP Application Source: https://context7.com/easysoft/zentaophp/llms.txt This is the entry point for all requests. It bootstraps the framework, loads common modules, parses the URL, and dispatches the request to the appropriate module and method. Ensure all required framework classes are included. ```php loadCommon(); // Parse the incoming URL to determine module + method $app->parseRequest(); // Load and execute the resolved module/method $app->loadModule(); // Output, stripping any UTF-8 BOM echo helper::removeUTF8Bom(ob_get_clean()); ``` -------------------------------- ### Blog Controller - Create Method Source: https://context7.com/easysoft/zentaophp/llms.txt Handles the creation of a new blog article via POST request. It sanitizes input, creates the article using the model, and redirects to the index page upon success or displays an error. ```APIDOC ## POST /blog-create.html ### Description Creates a new blog article based on POST data. Redirects to the index page on success or shows an error message. ### Method POST ### Endpoint /blog-create.html ### Parameters #### Request Body - **title** (string) - Required - The title of the blog article. - **content** (string) - Required - The content of the blog article. ### Response #### Success Response (200) Redirects to the blog index page. #### Error Response Displays an error message if creation fails. ``` -------------------------------- ### Short Helper Functions (inLink, cycle, getTime) Source: https://context7.com/easysoft/zentaophp/llms.txt Utilize convenient global functions for common tasks: `inLink()` for creating links to the current module, `cycle()` for alternating values in loops, and `getTime()` for retrieving microtime. ```php 5)); // link to current module's 'edit' method $val = cycle(array('odd', 'even')); // alternates on each call — useful in loops $time = getTime(); // microtime float ``` -------------------------------- ### Blog Model - getList Method Source: https://context7.com/easysoft/zentaophp/llms.txt Fetches a paginated list of all blog articles from the database. ```APIDOC ## Model Method: getList ### Description Retrieves a list of blog articles, supporting pagination. ### Parameters - **pager** (object) - Optional - Pagination object. ### Returns - (array) - An array of blog article objects. ``` -------------------------------- ### Blog Controller - apiCreate Method Source: https://context7.com/easysoft/zentaophp/llms.txt An AJAX-friendly endpoint for creating a blog article. It returns a JSON response indicating success or failure. ```APIDOC ## POST /blog/apiCreate ### Description Creates a blog article and returns a JSON response. ### Method POST ### Endpoint /blog/apiCreate ### Parameters #### Request Body - **title** (string) - Required - The title of the blog article. - **content** (string) - Required - The content of the blog article. ### Response #### Success Response (200) - **result** (string) - "success" - **data** (object) - Contains the ID of the newly created article. - **id** (int) - The ID of the created blog article. #### Error Response - **result** (string) - "fail" - **message** (object) - Error details. ``` -------------------------------- ### Blog Model - getWithAuthor Method Source: https://context7.com/easysoft/zentaophp/llms.txt Fetches a blog article and includes author information by loading the user model. ```APIDOC ## Model Method: getWithAuthor ### Description Retrieves a blog article and enriches it with the author's details by loading and querying the user model. ### Parameters - **id** (int) - Required - The ID of the blog article. ### Returns - (object) - The blog article object with embedded author information. ``` -------------------------------- ### Generate HTML, JS, and CSS with Helper Classes Source: https://context7.com/easysoft/zentaophp/llms.txt Use static classes like `html`, `js`, and `css` within view templates to generate frontend code. These helpers keep presentation logic clean and organized. ```php webRoot . 'favicon.ico'); echo html::a(helper::createLink('blog', 'view', "id=$article->id"), $article->title, "class='post-link'"); echo html::icon('edit'); // // Select dropdown $statusList = array('published' => 'Published', 'draft' => 'Draft'); echo html::select('status', $statusList, $article->status, "class='form-control'"); // JS helpers echo js::alert('Saved successfully!'); echo js::locate(helper::createLink('blog', 'index'))); // window.location = '...' echo js::locate('back'); // history.back() echo js::reload(); // window.location.reload() echo js::closeModal(); // Set a JavaScript variable from PHP echo js::set('config', array( 'webRoot' => $config->webRoot, 'requestType' => $config->requestType, )); // Outputs: var config = {"webRoot":"\/","requestType":"PATH_INFO"}; // CSS helpers echo css::internal($pageCSS); // inline Some text'; $config = HTMLPurifier_Config::createDefault(); $config->set('Filter', 'ExtractStyleBlocks', true); $purifier = new HTMLPurifier($config); $html = $purifier->purify($dirty); // This implementation writes the stylesheets to the styles/ directory. // You can also echo the styles inside the document, but it's a bit // more difficult to make sure they get interpreted properly by // browsers; try the usual CSS armoring techniques. $styles = $purifier->context->get('StyleBlocks'); $dir = 'styles/'; if (!is_dir($dir)) mkdir($dir); $hash = sha1($_GET['html']); foreach ($styles as $i => $style) { file_put_contents($name = $dir . $hash . "_$i"); echo ''; } ?>
``` -------------------------------- ### Module Link Generation with baseHelper Source: https://context7.com/easysoft/zentaophp/llms.txt Create internal module links using `helper::createLink()`. Supports passing parameters as an array or a query string. Generates PATH_INFO or GET-style URLs. ```php 5)); $link = helper::createLink('blog', 'view', 'id=5'); // PATH_INFO: /blog-view-5.html // GET: ?m=blog&f=view&id=5 ``` -------------------------------- ### Blog Controller - Index Method Source: https://context7.com/easysoft/zentaophp/llms.txt Handles the retrieval and display of a paginated list of blog articles. It utilizes the `pager` class for pagination and renders the `index.html.php` view. ```APIDOC ## GET /blog/ ### Description Retrieves a paginated list of blog articles and displays them. ### Method GET ### Endpoint /blog/ ### Parameters #### Query Parameters - **recTotal** (int) - Optional - Total number of records. - **recPerPage** (int) - Optional - Number of records per page. - **pageID** (int) - Optional - The current page ID. ### Response #### Success Response (200) - **view.title** (string) - The title for the blog index page. - **view.articles** (array) - An array of blog articles. - **view.pager** (object) - Pagination information. ### Request Example GET /blog/?recPerPage=10&pageID=2 ``` -------------------------------- ### Blog Controller - View Method Source: https://context7.com/easysoft/zentaophp/llms.txt Retrieves and displays a single blog article by its ID. ```APIDOC ## GET /blog-view-ID.html ### Description Fetches and displays a specific blog article by its ID. ### Method GET ### Endpoint /blog-view-[id].html ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the blog article to retrieve. ### Response #### Success Response (200) - **view.article** (object) - The blog article object. ### Request Example GET /blog-view-5.html ``` -------------------------------- ### config — Framework Configuration Source: https://context7.com/easysoft/zentaophp/llms.txt Manages framework settings through configuration files. Custom overrides are placed in `config/my.php`. ```APIDOC ## config ### Description Provides a mechanism for configuring the zentaoPHP framework. Settings are stored in `config/config.php` and can be overridden in `config/my.php`. ### Methods - **`set(string $key, mixed $value)`**: Sets a configuration value using dot-notation. ### Configuration Example (`config/my.php`) ```php db->host = 'localhost'; $config->db->port = '3306'; $config->db->name = 'myapp'; $config->db->user = 'root'; $config->db->password = 'secret'; $config->installed = true; // URL routing: PATH_INFO (pretty URLs) or GET (?m=module&f=method) $config->requestType = 'PATH_INFO'; $config->requestFix = '-'; // URL separator: /blog-view-1.html // Enable multi-language support $config->framework->multiLanguage = true; $config->default->lang = 'en'; $config->langs['en'] = 'English'; $config->langs['zh-cn'] = '简体中文'; // Enable the extension system (0=off, 1=common ext, 2=per-site ext) $config->framework->extensionLevel = 1; // Use dot-notation to set nested config values at runtime $config->set('db.strictMode', false); // Equivalent to: $config->db->strictMode = false; ?> ``` ``` -------------------------------- ### baseHelper - Static Utility Class Source: https://context7.com/easysoft/zentaophp/llms.txt A collection of static utility methods available globally. Covers link generation, file import, string utilities, date helpers, array access, and HTTP utilities. ```APIDOC ## baseHelper - Static Utility Class ### Description A collection of static utility methods available globally. Covers link generation, file import, string utilities, date helpers, array access, and HTTP utilities. ### Safe file import ```php // Safe file import (include-once by realpath) helper::import('/path/to/some/file.php'); ``` ### Create module links ```php // Create module links $link = helper::createLink('blog', 'view', array('id' => 5)); $link = helper::createLink('blog', 'view', 'id=5'); // PATH_INFO: /blog-view-5.html // GET: ?m=blog&f=view&id=5 ``` ### Safe array/object access with default ```php // Safe array/object access with default $value = zget($config->db, 'host', 'localhost'); // Returns $config->db->host if set, else 'localhost' $item = zget($_GET, 'page', 1); ``` ### Build SQL IN clause ```php // Build SQL IN clause $ids = array(1, 2, 3); $sql = "SELECT * FROM blog WHERE id " . helper::dbIN($ids); // => SELECT * FROM blog WHERE id IN ('1','2','3') $sql2 = "SELECT * FROM blog WHERE id " . helper::dbIN('1,2,3'); ``` ### Multibyte-safe string truncation ```php // Multibyte-safe string truncation $short = helper::substr('Hello World', 5, '...'); // => 'Hello...' ``` ### Date helpers ```php // Date helpers $now = helper::now(); // '2024-05-01 12:30:00' $today = helper::today(); // '2024-05-01' $time = helper::time(); // '12:30:00' $diff = helper::diffDate('2024-06-01', '2024-05-01'); // 31 ``` ### Check if AJAX request ```php // Check if AJAX request if(helper::isAjaxRequest()) { /* respond with JSON */ } ``` ### Get client info ```php // Get client info $browser = helper::getBrowser(); // ['name' => 'chrome', 'version' => '120'] $os = helper::getOS(); // 'Windows 10' $ip = helper::getRemoteIp(); // '192.168.1.1' ``` ### URL-safe base64 for use in PATH_INFO URLs ```php // URL-safe base64 for use in PATH_INFO URLs $encoded = helper::safe64Encode('some/path?query=1'); $decoded = helper::safe64Decode($encoded); ``` ### Short helper functions ```php // Short helper functions $link = inLink('edit', array('id' => 5)); // link to current module's 'edit' method $val = cycle(array('odd', 'even')); // alternates on each call — useful in loops $time = getTime(); // microtime float ``` ``` -------------------------------- ### Safe File Inclusion with baseHelper Source: https://context7.com/easysoft/zentaophp/llms.txt Include files safely using `helper::import()`, which performs an `include_once` based on the real path to prevent duplicate inclusions. ```php createLink()` for programmatic URL generation. ```php parseRequest(); // $app->moduleName === 'blog' // $app->methodName === 'view' // $app->params === ['id' => '5'] $app->loadModule(); // Includes module/blog/control.php // Instantiates class blog extends control // Calls blog->view(5) // To create URLs programmatically: $url = helper::createLink('blog', 'view', array('id' => 5)); // PATH_INFO mode: /blog-view-5.html // GET mode: ?m=blog&f=view&id=5 $url = helper::createLink('blog', 'index'); // /blog/ // Inside a controller you can also use: $url = $this->createLink('blog', 'view', 'id=5'); $url = $this->inlink('index'); // link to current module's index ``` -------------------------------- ### Load Models and Extensions Source: https://context7.com/easysoft/zentaophp/llms.txt Load other models using `$this->loadModel()` and encrypted extension classes using `$this->loadExtension()`. This allows modularity and reuse of code within the framework. ```php // ── Load a model from within another model ───────────────────────────────── // Inside any model: $this->loadModel('user'); $author = $this->user->getById($article->authorID); // ── Load an encrypted extension class ────────────────────────────────────── // Place encrypted logic in: module/blog/ext/model/class/analytics.class.php // class analyticssBlog { public function track($id) { ... } } $analytics = $this->loadExtension('analytics'); $analytics->track($id); ``` -------------------------------- ### Date and Time Helpers Source: https://context7.com/easysoft/zentaophp/llms.txt Utilize static methods for common date and time operations: `now()`, `today()`, `time()`, and `diffDate()` for calculating differences. ```php lang->blog->requiredFields = 'title,content,category'; ``` -------------------------------- ### Blog Model - getById Method Source: https://context7.com/easysoft/zentaophp/llms.txt Fetches a single blog article from the database by its ID. ```APIDOC ## Model Method: getById ### Description Retrieves a single blog article by its unique identifier. ### Parameters - **id** (int) - Required - The ID of the blog article. ### Returns - (object) - The blog article object. ``` -------------------------------- ### Blog Controller - Dashboard Method Source: https://context7.com/easysoft/zentaophp/llms.txt Embeds the output of another module's (e.g., blog's index) within the current view, useful for dashboards or composite views. ```APIDOC ## GET /blog/dashboard ### Description Fetches recent blog posts and assigns them to the view, allowing them to be displayed within the current template. ### Method GET ### Endpoint /blog/dashboard ### Response #### Success Response (200) - **view.recentPosts** (string) - HTML output of recent blog posts. ``` -------------------------------- ### Override View Files Source: https://context7.com/easysoft/zentaophp/llms.txt Replace the default view file for a module by placing a new file with the same name in the `ext/view/` directory. This completely changes the rendered output for that view. ```php // File: module/blog/ext/view/index.html.php // Replaces the default view completely for this module // ── Per-site extensions (extensionLevel = 2) ─────────────────────────────── // File: module/blog/ext/_mysite/model/getList.php // Only loaded when $app->siteCode == 'mysite' ``` -------------------------------- ### router::parseRequest() and router::loadModule() — Routing and Dispatch Source: https://context7.com/easysoft/zentaophp/llms.txt Handles URL parsing to determine the requested module and method, then dispatches the request to the appropriate controller action. ```APIDOC ## router::parseRequest() and router::loadModule() ### Description `parseRequest()` reads the incoming URL and sets `$app->moduleName` and `$app->methodName`. `loadModule()` then includes the module's `control.php`, instantiates the controller class, resolves URL parameters to method arguments via reflection, and calls the action. ### Methods - **`parseRequest()`**: Parses the incoming URL to set application module and method names. - **`loadModule()`**: Loads and executes the controller action for the parsed request. - **`helper::createLink(string $moduleName, string $methodName, array $vars = array(), string $க்குப் = '')`**: Creates a URL to a specific module and method. - **`inlink(string $methodName, array $vars = array())`**: Creates a link to a method within the current module. ### Usage Example ```php parseRequest(); // $app->moduleName === 'blog' // $app->methodName === 'view' // $app->params === ['id' => '5'] $app->loadModule(); // Includes module/blog/control.php // Instantiates class blog extends control // Calls blog->view(5) // To create URLs programmatically: $url = helper::createLink('blog', 'view', array('id' => 5)); // PATH_INFO mode: /blog-view-5.html // GET mode: ?m=blog&f=view&id=5 $url = helper::createLink('blog', 'index'); // /blog/ // Inside a controller you can also use: $url = $this->createLink('blog', 'view', 'id=5'); $url = $this->inlink('index'); // link to current module's index ?> ``` ``` -------------------------------- ### Blog Model - update Method Source: https://context7.com/easysoft/zentaophp/llms.txt Updates an existing blog article in the database. ```APIDOC ## Model Method: update ### Description Updates an existing blog article in the database. ### Parameters - **articleID** (int) - Required - The ID of the article to update. ### Returns None. ``` -------------------------------- ### Error Handling and Raw SQL with baseDAO Source: https://context7.com/easysoft/zentaophp/llms.txt Check for database errors using `dao::isError()` and retrieve error messages with `dao::getError()`. Fallback to raw SQL queries using `query()` when necessary. ```php dao->query("SELECT count(*) AS total FROM blog WHERE status = 'published'")->fetch(); echo $result->total; ``` -------------------------------- ### Database Transactions with baseDAO Source: https://context7.com/easysoft/zentaophp/llms.txt Manage database transactions using `begin()`, `commit()`, and `rollBack()`. Wrap critical operations within a try-catch block to ensure data integrity. ```php dao->begin(); try { $this->dao->insert('blog')->data($post)->exec(); $this->dao->insert('tag')->data($tag)->exec(); $this->dao->commit(); } catch (Exception $e) { $this->dao->rollBack(); } ``` -------------------------------- ### Fluent SELECT Queries with baseDAO Source: https://context7.com/easysoft/zentaophp/llms.txt Build complex SELECT queries using a chainable, SQL-injection-safe API. Supports WHERE, ORDER BY, and LIMIT clauses. Fetches results as an array of objects. ```php dao is the DAO instance. // SELECT with WHERE, ORDER, LIMIT $articles = $this->dao->select('id, title, date') ->from('blog') ->where('status')->eq('published') ->andWhere('date')->gt('2024-01-01') ->orderBy('date desc') ->limit(10) ->fetchAll(); // => array of stdClass objects // Fetch single record $article = $this->dao->select('*')->from('blog')->where('id')->eq(5)->fetch(); // => stdClass object or false // Fetch keyed by field $userMap = $this->dao->select('*')->from('user')->fetchAll('id'); // => array keyed by user.id // Fetch key=>value pairs (e.g. for