Page routing
Part of the sample code in this section is based on the demoPlugin plugin created by "Hello Z-Blog - Plugin Development";
There are two ways: "New Version - Page Routing" and "Old Version - Page Routing";
1.7 New Routing
Version 1.7 adds a routing system. Generally, as long as we inject a routing rule into the system and implement the function called by that route, passing an array parameter to that function upon successful matching, the routing function is implemented.
The key to adding a route item is the array that configures the routing rules. If you are unfamiliar with the routing system, please download the Z-Blog PHP Development Kit plugin from the application center and carefully study the routing rules that come with the system.
Example 1 (Staticizing Search Functionality)
Assumed Requirement 1:
Implement staticizing for the search function.
// Hook the function that injects the route to the interface
Add_Filter_Plugin('Filter_Plugin_Zbp_PreLoad', 'demoPlugin_RegRoute');
// Create a static routing rule for search and hook it to the Filter_Plugin_Zbp_PreLoad interface
function demoPlugin_RegRoute()
{
global $zbp;
$route = array(
'posttype' => 0, // Post type
'type' => 'rewrite', // Route type, can be active, rewrite, default
'name' => 'post_article_search', // Name
'call' => 'ViewSearch', // Function to call; upon successful match, call this function and pass an array of various matching parameters
'urlrule' => '{%host%}search/{%q%}_{%page%}.html', // Rule body
'args' => // Parameters for static routing (appearing in urlrule)
array(
'q' => '[^\\/_]+', // q is the search keyword, supports regex matching
'page', // page is the page number
),
'only_match_page' => false, // false means it can match URLs without a {%page%} parameter, which is the default behavior, so this line can be omitted
);
$zbp->RegRoute($route);
}
// The ViewSearch function is already written by the system, so just injecting the route can achieve staticizing of the search function!When the routing system matches a rule, it passes an array to the function specified by 'call'. The format is as follows:
function ViewSearch() {
// Get the parameters passed by the routing system. The routing system passes one and only one array containing various matching parameters.
$args = func_get_arg(0);
$q = $args['q']; // Get the query string
$page = $args['page']; // Get the page number, if it exists
// Get the Route route rule that successfully matched
$route = $args['_route'];
// You can print $args to view details
var_dump($args);
/*
// This array consists of posttype, various matching parameters, and the original rule
array(4) {
["q"]=>
string(7) "xxxxxxx"
["page"]=>
int(1)
["posttype"]=>
int(0)
["_route"]=>
array(10) {
// Routing rules...
// This section is omitted
}
}
*/
}Example 2 (Dedicated Download Page for Article Pages)
Assumed Requirement 2:
For visits matching the pattern {%host%}post/{%id%}.html, define another route {%host%}download/{%id%}.html to display download content.
Add the following interface hook to the ActivePlugin_demoPlugin() function:
Add_Filter_Plugin('Filter_Plugin_Zbp_PreLoad', 'demoPlugin_RegRoute');Interface function definition:
// Register a download page belonging to an article page and hook it to the Filter_Plugin_Zbp_PreLoad interface
function demoPlugin_RegRoute()
{
global $zbp;
$route = array(
// Default to 0, which is 'article', it is recommended to explicitly set it, indicating that the current route is related to this type, whether it's a single page or a list.
// You can set other values within $GLOBALS['posttype'] as needed, or add your own types, or set it to null to indicate it doesn't belong to any type.
'posttype' => 0, // 0 is article
// Route type (rewrite type uses route rules for matching, extracts parameters from the rules and passes them to call; if no match, it will skip this rule and proceed to the next)
'type' => 'rewrite',
// Route name, recommended format: prefix_route function
'name' => 'plugin_demoPlugin_download',
// Function called by the route
'call' => 'demoPlugin_ViewDownload',
// Original rule for dynamic and static routes (required)
'urlrule' => '{%host%}download/{%id%}.html',
// Extract values from the matched array of static rules and pass them as parameters to call (example: array('id', 'page') or array('cate@alias', 'page'))
'args' =>
array(
0 => 'post@id',
),
'verify_permalink' => false, // New parameter in 1.7.1, false means no comparison between the current URL and the target URL
);
$zbp->RegRoute($route);
}
// For accesses matched by the route, this function will be called
function demoPlugin_ViewDownload($arg)
{
// $arg is the array parameter passed by the routing system, including matched parameters and other information;
var_dump($arg);
$id = $arg["post"]; // Get the article ID
// Display the download page
// Implement your business logic here
}Example 3 (Implementing Content Pagination for Article Pages)
Assumed Requirement 3:
Paginate article content using a single rule.
Change '{%host%}post/{%id%}_{%page%}.html' to '{%host%}post/{%id%}_{%all%}.html', where {%all%} matches the content in the corresponding position.
Interface function definition:
function demoPlugin_RegRoute3()
{
global $zbp;
$route =
array(
'posttype' => 0,
'type' => 'rewrite',
'name' => 'plugin_demoPlugin_PostPagination',
'call' => 'demoPlugin_ViewPost',
'urlrule' => '{%host%}post/{%id%}_{%all%}.html',
'args' =>
array(
'post@id',
'all' => 'all|[0-9]+',
),
'verify_permalink' => false, // Do not compare if the current URL and target URL are the same
);
$zbp->RegRoute($route);
return true;
}
function demoPlugin_ViewPost($arg)
{
// $arg is the array parameter passed by the routing system, including matched parameters and other information;
var_dump($arg);
// Get the value from the array by index
$id = $arg["post"]; // Get the article ID
$isAll = $arg["all"];
if ($isAll == 'all') {
// Get the full text
// code
} else {
$page = $isAll;
// Paginate the article content and get the $page-th page;
// code
}
}Example 4 (Implementing Redirects within Routing Rules)
Assumed Requirement 4:
Use routing rules to implement 301, 302 redirects.
// The routing rule is as follows. Inject it into the routing system using $zbp->RegRoute() to implement it.
// The type of this routing rule is the default 'default'. It can take effect in both static and dynamic modes!
$route = array(
'posttype' => 0,
'type' => 'default',
'name' => 'plugin_redierct_to_baidu',
'urlrule' => '{%host%}baidu.html',
// redirect_to is an http302 redirect. If you need a 301 redirect, the key name should be redirect301_to
'redirect_to' => 'https://www.baidu.com/',
);
$zbp->RegRoute($route, true); // Add the second parameter 'true' here to prepend the route to the front
// Visiting https://yourwebsite.com/baidu.html will redirect to https://www.baidu.com/Example 5 (Implementing 301 Redirects for Website Restructuring)
Assumed Requirement 5:
Supported in version 1.7.2 and above.
Before the website restructuring, the permalink format for articles was https://yourwebsite.com/post/{%id%}.html
After restructuring, the new URL format for articles is https://yourwebsite.com/article/{%alias%}.html
// Define 301 rewrite rules and inject them into the system
$route = array(
'posttype' => 0,
'type' => 'rewrite',
'name' => 'plugin_post_article_redierct301',
'urlrule' => '{%host%}post/{%id%}.html',
'call' => 'post_article_redierct301',
'args' => array('id'),
);
$zbp->RegRoute($route);
// Define the Call function and implement HTTP 301 redirects
function post_article_redierct301($arg){
global $zbp;
$id = $arg["id"]; // Get the article ID
$post = $zbp->GetPostByID($id);
// Assemble the new URL
$url = $zbp->host . 'article/' . rawurlencode($post->Alias) . '.html';
// Return 301 redirect data
return array('StatusCode' => 301, 'Location' => $url);
}Example 6 (Implementing Static URL Access for APIs)
Assumed Requirement 6:
Supported in version 1.7.2 and above.
The default API access is https://yourwebsite.com/zb_system/api.php?mod=post&act=get&id=1
In static mode, it can be accessed as https://yourwebsite.com/api/post/get/?id=1
// Define API rewrite rules and inject them into the system
$zbp->RegRoute(
array(
'posttype' => null,
'type' => 'rewrite',
'name' => 'rewrite_api',
'call' => 'Rewrite_API',
'urlrule' => '{%host%}api/{%mod%}/{%act%}/',
'args' =>
array(
'mod' => '[_a-zA-Z0-9]+',
'act' => '[_a-zA-Z0-9]+',
),
)
);
// Define the Call function
function Rewrite_API(){
global $zbp;
// Mark as API running mode
defined('ZBP_IN_API') or define('ZBP_IN_API', true);
ApiCheckEnable();
foreach ($GLOBALS['hooks']['Filter_Plugin_API_Begin'] as $fpname => &$fpsignal) {
$fpname();
}
ApiCheckAuth(false, 'api');
ApiCheckLimit();
$GLOBALS['mods'] = array();
$GLOBALS['mods_allow'] = array();
$GLOBALS['mods_disallow'] = array();
$fpargs = func_get_arg(0);
$GLOBALS['mod'] = strtolower($fpargs['mod']);
$GLOBALS['act'] = strtolower($fpargs['act']);
// Load system and application mods
ApiLoadMods($GLOBALS['mods']);
// Perform API whitelist and blacklist checks
ApiCheckMods($GLOBALS['mods_allow'], $GLOBALS['mods_disallow']);
ApiLoadPostData();
ApiVerifyCSRF();
// Dispatch API
ApiDispatch($GLOBALS['mods'], $GLOBALS['mod'], $GLOBALS['act']);
}1.6 and Older Versions
Assumed Requirement:
For visits matching the pattern {%host%}post/{%id%}.html, define another route {%host%}download/{%id%}.html to display download content.
Add the following interface hook to the ActivePlugin_demoPlugin() function:
Add_Filter_Plugin('Filter_Plugin_ViewAuto_Begin', 'demoPlugin_Rewrite');Interface function definition:
function demoPlugin_Rewrite($original_url, $url)
{
global $zbp;
$r = UrlRule::OutputUrlRegEx("{%host%}download/{%id%}.html", 'article');
// debug
// ob_clean();
echo __FILE__ . "丨" . __LINE__ . ":
\n";
var_dump($r); // string(38) "/(?J)^download\/(?P[0-9]+)\.html$/"
echo "
\n\n";
// die();
// debug
$m = array();
if (preg_match($r, $url, $m) == 1) {
// debug
// ob_clean();
echo __FILE__ . "丨" . __LINE__ . ":
\n";
var_dump($m);
echo "
\n\n";
// die();
// debug
/**
* array(3) {
* [0]=>
* string(16) "download/32.html"
* ["id"]=>
* string(2) "32"
* [1]=>
* string(2) "32"
* }
**/
// $m['id'] can be used as a parameter for querying and outputting;
// You can also use ViewPost($m) combined with interfaces like Filter_Plugin_ViewPost_Template;
unset($m[0]); // Due to the side effects of the new mechanism, additional processing is currently required before passing values;
ViewPost($m);
// Skip subsequent operations in the same interface queue
$GLOBALS['hooks']['Filter_Plugin_ViewAuto_Begin']['demoPlugin_Rewrite'] =
PLUGIN_EXITSIGNAL_RETURN;
}
}Article link: https://docs.zbp.cool/zblogdocs/zblogapp/13.html
Helpful?
2025-10-09 20:36:57