在面向对象的 PHP 项目中组织文件和文件夹的最佳方法是什么? [英] What is the best way to organize files and folders in an object oriented PHP project?
问题描述
面向对象的 PHP 项目的最佳目录结构是什么?在其他因素中考虑安全性.我通常使用这些技术来构建网站:OOP PHP/MySql、html、css、javascript/jQuery、ajax 和 smarty.而且我现在不想使用框架.
What is the best directory structures of an object oriented PHP project? taking security into consideration among the other factors. I usually use these technologies to build websites: OOP PHP/MySql, html, css, javascript/jQuery, ajax and smarty. And I don't want to use a framework right now.
推荐答案
只需使用 namespaces 带有 autoloader.
这样你就可以这样组织你的文件夹:
This way you can organize your folders this way:
/
src
Model
User.php
View
index.php
Controller
HomeController.php
assets
img
js
css
您的 User
类将类似于:
namespace Model;
class User{ ... }
你可以这样引用:
$user = new \Model\User;
或:
<?php
use \Model\User;
...
// later in your code
$user = new User;
魔法在哪里?当您请求一个类时,自动加载器需要它[并在出现任何问题时抛出异常].
Where's the magic? When you ask for a class, the autoloader requires it [and throws an exception if anything goes wrong].
一个基本的自动加载器看起来像:
A basic autoloader will look like:
spl_autoload_register(function ($class) {
include 'src' . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
});
它将根据类名从 src
文件夹中搜索类,在本例中为 Model\User
.
It will search classes from src
folder based on class name, in this case Model\User
.
这些是基础,你可以稍微调整一下.
These are the basics, it's up to you to tweak it a bit.
这篇关于在面向对象的 PHP 项目中组织文件和文件夹的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!