문제

I'm trying to get value from the core_config_data table but when I follow various guides on the internet or previous topics here, it doesn't work..

Disclaimer: I'm new to PHP and Magento in general so I'm not completely sure what I'm doing..

The class is:

class Db
{
    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig)
    {
        $this->_scopeConfig = $scopeConfig;
    }

    public function getApiKey()
    {
        $getApiKey = $this->_scopeConfig->getValue('vendor_module/general/ApiKey',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        return $getApiKey;
    }
}

When I try to instantiate the class by calling $new = Db(); $new->getApiKey; it returns the below error:

Fatal error: Uncaught ArgumentCountError: Too few arguments to function vendor\module\src\Model\Db::__construct(), 0 passed in /xxxxx/src/Model/Db.php on line 23 and exactly 1 expected in /xxxxx/src/Model/Db.php on line 9

I have tried to re-run setup:di:compile cleared cache folders, removed contents of magento/generated (I don't have var/generation in magento 2.2.0..) and still nothing.

Links I'm aware of: How to get value from `core_config_data` table in Magento 2

https://maxyek.wordpress.com/2015/04/03/building-magento-2-extension-extendedconfig/

http://magehelper.blogspot.co.uk/2015/06/get-system-config-values-in-magento-2.html

Any help will be much appreciated.

도움이 되었습니까?

해결책

Instead of creating a Db object directly, which doesn't make use of Magento's Dependency Injection (DI) functions, you should either:

  1. Use DI to inject your Db object directly in the __constructor() of the class you are using it in:

    public function __construct(\Path\To\Your\Class\Db $db)
    {
        // now your Db class is instantiated with the 
        // ScopeConfigInterface as expected
        $this->db = $db;
        // use as you will
        $this->db->getApiKey();
    }
    

or

  1. Create it with a "Factory" class (if you need more than one instance)

    public function __construct(\Path\To\Your\Class\DbFactory $dbFactory)
    {
        // this "virtual" class dbFactory let's you create Db objects, 
        // populated with your DI objects like ScopeConfigInterface
        $this->dbFactory = $dbFactory;
        // here's how to create a Db object from the Factory
        $db = $this->dbFactory->create();
        // use as you will
        $db->getApiKey();
    }
    

다른 팁

Your script does not works because of missing argument in constructor, when you call $new = Db(); you should pass the instance of \Magento\Framework\App\Config\ScopeConfigInterface inside it, like:

$new = Db($scopeConfig);

Where the $scopeConfig instance of \Magento\Framework\App\Config\ScopeConfigInterface

You can find an info about "How to run external script in Magento 2" here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top