如何从使用Composer自动加载的自定义插件中使用woocommerce类 [英] How to use woocommerce classes from a custom plugin that uses composer autoload

查看:147
本文介绍了如何从使用Composer自动加载的自定义插件中使用woocommerce类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在插件中使用Composer自动加载功能,使管理所有文件和类变得更加容易,而不是每次都写require_once

但是,我在尝试访问本地woocommerce类时遇到了麻烦.我的类是使用命名空间定义的,例如:

<?php
namespace Inc\Api;

class RestClientApi
{
....
}

例如,如果我尝试在此类中调用woocommerce类:

<?php
namespace Inc\Api;

class RestClientApi
{

  public $example = new WC_product();

}

我收到错误消息Class Inc/Api/WC_product not found我知道错误的含义,但是考虑到我在自定义插件类中使用了自动加载和命名空间,因此我不知道如何从自定义插件中使用Woocommerce类.

更新 根据要求,我添加了我的自动加载配置,这非常简单,我只是调用了/inc文件夹

"autoload": {
        "psr-4": {"Inc\\": "./inc"}
    }

解决方案

在您的插件composer.json中,添加以下内容(您可以根据需要进行调整):

    "autoload": {
        "psr-4": {
            "WooCommerceNamespace\\":"path/to/woocomerce/classes/folder"
        }
    },

然后运行

 composer dump-autoload 
 

在composer.json文件夹中.

然后将其添加到插件文件中:使用WooCommerceNamespace \ WC,并且WC类现在应该可用了.

(如果您的WC.php文件已经具有名称空间声明,请在psr-4声明中使用该名称空间).

Im using Composer autoload in my plugin to make it easier to manage all the files and classes instead of writing everysingle time require_once

However Im having trouble trying to access native woocommerce classes. My classes are defined with namespaces as for example:

<?php
namespace Inc\Api;

class RestClientApi
{
....
}

If I try to call a woocommerce class within this class for example:

<?php
namespace Inc\Api;

class RestClientApi
{

  public $example = new WC_product();

}

I get the error Class Inc/Api/WC_product not found I know what the error means, but I don't have idea how to use Woocommerce classes from my custom plugin, considering I'm using autoload and namespaces in my custom plugin classes.

UPDATE As requested I added my autoload configuration, it is pretty simple, Im just calling my /inc folder

"autoload": {
        "psr-4": {"Inc\\": "./inc"}
    }

解决方案

In your plugin composer.json, add something like this (you adapt it to your needs):

    "autoload": {
        "psr-4": {
            "WooCommerceNamespace\\":"path/to/woocomerce/classes/folder"
        }
    },

Then run a

composer dump-autoload 

inside the composer.json folder.

Then add to your plugin file: use WooCommerceNamespace\WC and the WC class should now be available.

(if your WC.php file already has a namespace declaration, use that namespace in your psr-4 declaration).

这篇关于如何从使用Composer自动加载的自定义插件中使用woocommerce类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆