php - 轻量级、基于 PHP 的布局框架……知道吗?

标签 php layout frameworks

<分区>

我正在寻找一个轻量级的、基于 PHP 的布局框架。就像 Zend Framework 如何使用布局一样,我想创建一个布局模板并仅包含必要页面的内容。

<html>
<head>
<title><?= $pageTitle ?></title>
</head>
<body>
<?= $content ?>
</body>
</html>

有人知道这样做的吗?我会使用 Zend Framework,但它对我想要实现的目标来说太多了。

最佳答案

我投票支持 PHP。 (PHP 一个模板引擎。)

function template($file, $vars) {
  ob_start();
  if(count($vars) > 0) { extract($vars); }
  include 'views/'.strtolower($file).'.php';
  return ob_get_clean();
}

顺便说一句,您可以执行以下操作。

echo template('layout', array( 'content' => template('page', $myData) ));

当 PHP 本身仅需 6 行就足够时,您是否还需要使用另一个模板/布局引擎?

编辑:

也许我不清楚它是如何工作的。

template() 以模板名称(也用于组织工作的子目录)调用,并以数组对象作为第二个参数。如果给定的变量不为空,例如 template('index',null) 为空,则该数组将被视为关联数组:并且每个键都成为包含值的变量。

所以逻辑变成:

template('my_template', array(
  'oranges' => 'apples'
));

“views/my_template.php”是:

<html>
<head>
  <title>Are apples == <?= $oranges ?>?</title>
</head>
<body>
  <p style="color: <?= $oranges == 'oranges' ? 'orange" : 'darkgreen' ?>">
    Are apples == oranges?
  </p>
</body>
</head>

因此,每次使用变量 $oranges 时,PHP 都会获取从数组 $vars['oranges'] 导出的数据。

因此,所有输出随后都由 ob_get_clean() 获取并作为字符串返回。要输出此字符串只需 echoprint,或将其分配给一个数组以作为内容传递给布局。如果您了解这一点,那么就可以很容易地采用我所写的内容并从中制作布局,或者使用逻辑输出 JSON 的页面。

我建议您在放弃之前先试验一下这个答案。它有在你身上成长的趋势。

编辑 2:

根据要求,我将展示我的项目将使用的目录布局。请注意,其他 MVC 框架使用不同的结构。但是,我喜欢我的简单。

index.php
application/
  framework.php
  controllers/
    welcome.php
views/
  template.php
  index.php

为了安全起见,我有一个 .htaccess 文件,它将每个请求(除了那些发送到 js/css/ 的请求)路由到index.php 脚本,有效地隐藏了我的目录。如果您愿意,您甚至可以通过模板制作 CSS,我已经这样做了,以便使用变量等。

因此,对 template('template', array()) 的任何调用都会自动加载文件 ./views/template.php。如果我在名称中包含斜杠,它就会成为路径的一部分,如下所示:./views/posts/view.php

编辑 3:

thanks for your update. So you must have some code in your index.php file that routes the requested url to the appropriate controller, correct? Could you show some of this? Also, it doesn't look like your views mirror your controller directory. Can you explain a little more how urls map to controllers and/or views? What do you have in framework.php? What does it do? Thanks!

我展示的代码是我的 Web 开发专用框架的一小部分。 I've talked already about potentially releasing it具有双重许可,或作为商业用途的捐赠软件,但在短时间内(15-21 天)其他任何人都无法编写。如果你愿意可以read my source code on GitHub ...但请记住,它仍然是 alpha Material 。

许可证是Creative Commons SA .

关于php - 轻量级、基于 PHP 的布局框架……知道吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/953675/

相关文章:

javascript - 如何将连接到外部数据库的外部 php 文件中的数据发送到我的扩展程序的 content-script.js?

phpinfo 和 php -v 在 lion 上显示不同的版本

css - "left"和 "right"是非语义 CSS 类名吗?

HTML CSS 主体自动调整大小

php - CakePHP 到 CodeIgniter 的转换

Php - 如何从 mysql 中排除数据

php - 在 bit.ly API 中使用 oauth 访问 token 和登录/apikey 之间的区别

android - 如何获取Android系统偏好设置?

swift - 只有特定的包标识符找不到框架错误

ios - "No such module"每次打开项目时第 3 方框架导入问题