wpackagist-plugin / wpal-autoload
Wp Autoload with Namespaces(用于使用面向对象的插件编写更佳、更干净的代码)
1.1.2
2018-02-13 11:27 UTC
Requires
- php: >=5.3.2
This package is not auto-updated.
Last update: 2024-09-21 16:01:04 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/文件夹。 - 登录到你的管理员账户并启用插件以使用它。