まず第一に、クリーンで保守可能なコードを記述したい場合は、エラーサプレッサーを使用しないでください@
。大小のすべてのエラーをリッスンします。これは大いに役立ちます。本当に。
error_reporting(E_ALL);
終わったら、変更するだけです
error_reporting(0);
関数(たとえば、loadPageProfile)に物を入れると、見た目が非常に乱雑になる可能性があるため、私は物をモジュールに入れようとしています。
さて、あなたは正しい軌道に乗っています...あなたがしなければならないのは、のような1つのモジュールを作成することです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);
}
}
}
contact
ここでindex
、ページがあると仮定します: 、、、、、したがってprofile
、どこでも使用する代わりに、login
単にその「快適な」メソッドを呼び出します。register
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を混在させないでください(分離されたcssファイルを作成し、それを特定のページに含めます。<link href="path_to_css.css" rel="stylesheet" type="text/css" />
マークアップが明確になり、将来的に保守しやすくなるため(たとえば、スタイルを変更したり、何かを追加したりする場合)
2)PHPとJavaScriptのコードを混在させないでください。JavaScriptファイルをCSSと同様に別々のファイルに保存します。PHPとJavaScriptの間で変数を共有するためにAjaxを使用する
3)すべてのHTML、CSS、JavaScriptをPHPと混合しないでください。特にHTML。それmodules
(クラスまたはビジネスロジック)を別々のファイルに保存します。次に、特定のタスクに必要な部分を含めます。