imranz / wp-autoload
1.1.2
2018-02-13 11:27 UTC
Requires
- php: >=5.3.2
This package is not auto-updated.
Last update: 2022-02-01 13:07:24 UTC
README
一个插件,旨在简化使用命名空间,并使其他插件使用命名空间加载文件变得更加容易。它可以消除include_once, require_once, include 和 require,因为这些方法会使你的代码看起来更丑,也更难维护。为了正确包含其他类或函数,你需要添加一些路径,然后指定带有完整路径的文件名。
此插件需要你有自由来编写和根据所需的目录结构来组织你的代码。
指南
你需要遵循的唯一指南如下
- 对分离的类和函数使用命名空间,例如,放置在
wp-content/plugins/TestPlugin/inc中的任何内容应该使用命名空间TestPlugin\inc。而放置在wp-content/plugins/TestPlugin/Inc中的任何内容应该使用命名空间TestPlugin\Inc。 - 文件名应与类名相同,但大小写无关,因为如果类名是
Test且文件名是test.php,自动加载器仍然能够加载正确的文件。
使用方法
现在让我们看看如果你遵循上述指南通过命名空间来维护代码,它将如何帮助你维护代码。
在你的主插件文件中添加以下行
include_once(WP_PLUGIN_DIR . "/wpal-autoload/wpal-autoload.php" );
包含类和函数的代码
wpal_load(PluginNamespace\SubNamespace\ClassName);
//or in case calling from the code which comes in same namespace use the below code
wpal_load(ClassName::class);
//now after using the above code the class or fuction is now included and can be called or used
$classObj = new ClassName($param1, $param2);
即使不使用上述代码,你也可以直接创建类的实例,因为插件会自动包含那些文件,并返回实例。
/* wpal_create_single_instance: will only create a single instance of the class and save it for later use so this will
* make sure only one instance of the class is created.
*/
wpal_create_single_instance(PluginNamespace\SubNamespace\ClassName);
//or depending on your namespace
wpal_create_single_instance(ClassName::class);
/* wpal_create_instance: will first check if the instance is already created by wpal_single_create_instance,
* if found would use that otherwise would create new one.
*/
wpal_create_instance(PluginNamespace\SubNamespace\ClassName);
//or depending on your namespace
wpal_create_instance(ClassName::class);
/* wpal_new_instance: will always create new instance of the class.
*/
wpal_new_instance(PluginNamespace\SubNamespace\ClassName);
//or depending on your namespace
wpal_new_instance(ClassName::class);
//So now you don't need to write $classObj = new ClassName(), you can just use those methods to create it.
安装
- 下载插件,将其重命名为
wpal-autoload或WpalAutoload,然后将其放置在wp-content/plugins/文件夹中。 - 登录到你的管理员账户,启用插件以使用它。