Reputation: 175
I am using ObjectManager::get in the following way:
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$sqlSel = $objectManager->get('HGA\\Mairlist\\Utilities\\SqlSelect');
$Setup = $sqlSel->getUid("cr", "lastplay", 3);
I have read
several times, but I don't understand it. With $objectManager->get('HGA\\Mairlist\\Utilities\\SqlSelect')
I got a pointer to this function, but how should do it with Service $service
?
How do I get a pointer to my program?
Upvotes: 0
Views: 1357
Reputation: 1956
You are talking about DI (Dependency Injection). The objectManager->get()
has been marked as deprecated it will be removed on TYPO3 12. That means that it has to be replaced either with DI or with the GeneralUtility::makeInstance depending on the usage.
The recommended way to inject your dependencies in your constructor. In your case, it would look like this:
use HGA\Mairlist\Utilities\SqlSelect;
class YourClass
{
/**
* @var SqlSelect
*/
protected $sqlSel;
public function __construct(SqlSelect $sqlSel)
{
$this->sqlSel = $sqlSel;
}
public function yourMethod()
{
$Setup = $this->sqlSel->getUid("cr", "lastplay", 3);
}
}
Another way to do it is how Georg described. You can use the GeneralUtility::makeInstance()
use HGA\Mairlist\Utilities\SqlSelect;
class YourClass
{
public function yourMethod()
{
$sqlSel = GeneralUtility::makeInstance(SqlSelect::class);
$Setup = $sqlSel->getUid("cr", "lastplay", 3);
}
}
In both cases, you have to remember, in order for the DI to work, the class has to be set on PUBLIC otherwise you will get the following error:
Too few arguments to function HGA\Mairlist\Utilities\SqlSelect::__construct(), 0 passed in /path/to/your/typo3/installation/typo3/sysext/core/Classes/Utility/GeneralUtility.php on line 3691 and exactly 1 expected
and you can do that on your Services.yaml
your_extension/Configuration/Services.yaml
# Configuration/Services.yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
HGA\Mairlist\:
resource: '../Classes/*'
HGA\Mairlist\Utilities\SqlSelect:
public: true
After all that you need to clear all cache, specially the ones that are under the Maintenance Module.
Hope it was helpful.
Best regards
Upvotes: 1
Reputation: 7939
If you don't use extbase you could use
$sqlSel = GeneralUtility::makeInstance('HGA\\Mairlist\\Utilities\\SqlSelect');
Upvotes: 0