赵二华 / php-router-template
一个简单的PHP类,帮助在路由器中渲染模板并修复额外的斜杠问题。
1.6
2022-11-15 18:41 UTC
Requires
- php: >=5.3.0
README
一个简单的PHP类,帮助在路由器中渲染模板并修复额外的斜杠问题。
重要
您不必安装、下载或使用此类,我编写此类是为了满足个人需求,第一次在我项目中开始使用路由器代替旧方式。关于此类的唯一重要之处在于 deep
方法,它解决了在StackOverflow问题中提到的额外斜杠问题 在路由后添加斜杠 / 时样式消失
并使我在不使用任何PHP框架的情况下轻松访问模板中的任何定义的全局变量。所以请忽略此项目,尽管我已清楚地记录了类并展示了使用示例,但这因为我喜欢编写美观的代码,并且喜欢将所有编写的函数封装在类中,因为将来可能需要它们。关于Composer安装?是的,我知道,它是免费的,所以我使用了它。
通过Composer安装非常简单
composer require peterujah/php-router-templete
用法
使用必要的参数初始化RouterTemplate并注册您自定义的类。
$template = new \Peterujah\NanoBlock\RouterTemplate(__DIR__, false); $template->addUser(new User(User::LIVE))->addFunc(new Functions())->addConfig(new Config());
通过传递目录的deep方法作为第一个参数来渲染模板,可选的选项数组将是第二个参数。
$template->Render("home")->with($template->deep(1));
使用上述方法的简写应该使用 withDept
方法,只需传递目录dept整数作为第一个参数,可选的选项数组将是第二个参数。
$template->Render("home")->view(1);
使用Bramus Router或任何其他PHP路由器。初始化您的路由器实例
$router = new \Bramus\Router\Router();
使用with
和deep
方法渲染主页模板。
$router->get('/', function() use ($template) { $template->Build("home")->with($template->deep(0)); });
使用view
方法渲染主页模板。
$router->get('/', function() use ($template) { $template->Build("home")->view(0); });
使用产品ID作为第二个URL参数渲染更新产品模板。
$router->get('/update/([a-zA-Z0-9]+)', function($id) use ($template) { $template->Build("product")->view(1); /* Using with method below $template->Build("product")->with($template->deep(1)); */ });
使用产品ID作为第二个URL参数并传递额外的选项到模板中渲染更新产品模板。
$router->get('/update/([a-zA-Z0-9]+)', function($id) use ($template) { $template->Build("product")->view(1, [ "foo" => "Our Foo" "bar" => "Our Bar id {$id}" ]); });
访问模板文件/router/product.php
中的所有全局变量。
<?php /*Secure template from unwanted access*/ $ALLOW_ACCESS or die("Access Denied"); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Router template</title> <!-- Unbreakable css path --> <link href="<?php echo $root;?>assets/bootstrap/css/bootstrap.min.css" rel="stylesheet"/> </head> <body> <h1>News - <?php echo $config::NAME;?></h1> <?php /* Call Functions methods */ $func->doStuff(); /* Call User methods */ $user->doAnything() /* Gets user information */ $person->name; /* Access options from template */ echo $self["foo"]; /* Project root directory */ echo $root; ?> Unbreakable image <img src="<?php echo $root;?>assets/image/foo.png"/> Unbreakable link <a href="<?php echo $root;?>newpage">A New Page</a> </body> </html>