PHP编码风格和约定:使用require加载页面元素



我最近开始使用PHP构建网页,由于缺乏经验,我对编码约定有疑问。使用require动态加载网页中的页面内容或页面元素是否被认为是糟糕的风格?

例如,如果您正在对代码进行模块化,并且有一个/resources/pageContent/文件夹,其中包含包含不同页面内容的不同文件。说require ("resources/pageContent/profile.php")会被认为是不好的风格吗?我看到的另一种方法是使用fopen(),但当然,它不允许在动态加载的页面中使用任何PHP代码,并且只打印HTML和CSS。

我只是想把东西放进模块中,因为把东西放在函数中(例如loadPageProfile)可能会看起来很乱。

首先,如果您想编写干净且可维护的代码,请不要使用错误抑制器@倾听所有的错误——大大小小的错误。这将对你大有帮助。真正地

error_reporting(E_ALL);

完成后,只需更改

error_reporting(0);

我只是想把东西放进模块,因为把东西放在函数(例如loadPageProfile)可能看起来非常混乱。

好吧,那么你就走上了正轨。。。您所要做的就是创建一个名为Page的模块。(我们现在谈论的是页面)

使用过程代码来创建模块是一种糟糕的做法,因为我们正在讨论它们。

只需将所有逻辑封装到一个类中,如下所示:

文件Page.php

abstract class Page {
/**
* Includes chunk of the page
* it's Useful, when you have number of pages
* and want for example only one chunk to be displayed
* everywhere
* This could be footer or menu or something like this "static" parts
* 
* @param string $block
* @return void
*/
public static function useBlock($block)
{  
$file = 'path_to_blocks' . DIRECTORY_SEPARATOR . $block; 
//Ensure this is valid stream before we include it;
if ( is_file($file) ){
// No need to use require() here
// Because we are sure that file exists and valid for inclusion
// include is a bit faster that require()
include($file);
}
}
/**
* Displays some page
* This is just simply form of require, but
* this method would simplify inclusion 
* 
* @param string $page
* @return void
*/
public static function DisplayPage($page)
{
$file = 'path_to_your_pages' . DIRECTORY_SEPARATOR . $page;
if ( is_file($file) ){
include($file); 
}
}
}

现在假设您有页面:contactindexprofileloginregister,所以您不必在任何地方使用require(),而只需将其称为"舒适"方法。

而页脚和菜单可能与以下类似:

文件:footer.phtml

<div id="footer">Copyrigth (c) you and bla bla bla</div>

文件:menu.phtml

<li><a href="/">Home</li>
<li><a href="/register/">Register</a></li>
<li><a href="/contact/">Contact</li>

为了需要您可以创建的特定类,也可以创建一些module,比如这个:

class Import {
/**
* 
* @param string $class Class File name to be required
* @param string $ext filename extension (just to simplify )
* @return bool
*/
public static function getSomeClass($class, $ext = '.php'){
$location = 'folder_of_classes' . DIRECTORY_SEPARATOR . $class . $ext;
return spl_autoload_register(function() use ($location){
// We won't use include() here
// Because we'd to stop (producing fatal error) if inclusion would fail
require_once ($location);
});
}
}

然后,当你需要特定的课程时,只需致电

<?php
// requires MySQL_PDO.php located in defined foldet
Import::getSomeClass('MySQL_PDO');

请记住,当我们谈论模块时,在99%的情况下,我们谈论的是在这个模块中实现的类。

另一个建议是:

1) 不要将CSS与HTML混合(通过<link href="path_to_css.css" rel="stylesheet" type="text/css" />创建分离的CSS文件并将其包含在特定页面上

因为它使标记清晰明了,便于将来维护(比如当你想更改样式或添加一些东西时)

2) 不要混合PHP和JavaScript代码。将JavaScript文件和CSS分别保存在不同的文件中。使用Ajax在PHP和JavaScript 之间共享变量

3) 不要把所有的HTML、CSS、JavaScript和PHP混合在一起。尤其是HTML。将modules(类或业务逻辑)保存在单独的文件中。然后只需包含特定任务所需的部分。

不,这不是一种糟糕的风格,实际上是一种很好的做法。继续使用它。

最新更新