Symfony 4.0 Translator class not injected to controller - dependency-injection

I got a problem in new symfony 4.
<?php
namespace App\Controller;
use App\Entity\Flight;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Form\FlightType;
use Symfony\Component\Translation\Translator;
use Symfony\Component\HttpFoundation\Request;
/**
* Class DefaultController
* #package App\Controller
*/
class DefaultController extends Controller
{
/**
*
* #Route("/")
* #Route("/{_locale}/", name="homepage", requirements={"_locale" = "%app.locales%"})
*
* #param Translator $translator
* #param Request $request
*
* #return \Symfony\Component\HttpFoundation\RedirectResponse|Response
*/
public function index(Translator $translator, Request $request)
{
$translated = $translator->trans('Symfony is great');
Error:
Controller "App\Controller\DefaultController::index()" requires that you provide a value for the "$translator" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
Configs:
service.yaml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
...
App\Controller\:
autowire: true
resource: '../src/Controller'
tags: ['controller.service_arguments']
translation.yaml
framework:
default_locale: '%locale%'
translator:
paths:
- '%kernel.project_dir%/translations'
fallbacks: ['en']
Whats wrong? Manual here:
http://symfony.com/doc/current/translation.html

Found the answer.
bin/console cache:clear did not clear messages cache. Helped just hard remove var/cache folder.
I have used Action(TranslatorInterface $translator) for inject to controller action (Probably bug in docs)
$translator->trans('id') doesn't work with ids. It work when using trans-unit sourse tag.

Related

TYPO3 v 11 : dependency injection generates Object of class Aip\Bit3\Domain\Repository\AbstractRepository could not be converted to string

I'm trying to port a backend module from TYPO3 10 to TYPO3 11.
I have already made dependency injection working moving the repository variable from protected to public, but this way of working is already deprecated and will be removed in TYPO3 12
I used the guide here to define a repository variable in my controller and instantiate it:
class ModuleConfController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
/**
* #var \Aip\Bit3\Domain\Repository\AbstractRepository
*
*/
private ?AbstractRepository $abstractRepository = null;
public function injectAbstractRepository(AbstractRepository $abstractRepository)
{
$this->$abstractRepository = $abstractRepository;
}
I have also defined a Services.yaml file with this content:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
Aip\Bit3\:
resource: '../Classes/*'
exclude: '../Classes/Domain/Model/*'
The code seems to work since the inject injectAbstractRepository is called and the parameter is populated with an instance of the class AbstractRepository.
But instead of assinging the value to the class field it throws an exception
Object of class Aip\Bit3\Domain\Repository\AbstractRepository could not be converted to string
Can someone shed some light?
The comment made by Thomas Loffer solved the problem. I had improperly used cut and paste to write the wrong line and misled by the error message

Can't inject repository on some controller Typo3

In my custom controller, i'm trying to inject a repository as a dependecy, like this
class FundedProjectController extends ActionController {
/**
* #var \GeorgRinger\News\Domain\Repository\NewsRepository
*/
protected $newsRepository;
/**
* Inject a news repository to enable DI
*
* #param \GeorgRinger\News\Domain\Repository\NewsRepository $newsRepository
*/
public function injectNewsRepository(\GeorgRinger\News\Domain\Repository\NewsRepository $newsRepository)
{
$this->newsRepository = $newsRepository;
}
...
But when I call it in my previewAction, i have an error saying that my $this->newsRepository is null.
But this injection is working on this controller, but I can't figure out why...
class NewsController extends NewsBaseController
I'm working on 7.6.32, stagging website but production mode enable, all caches cleared (also tried with ?no_cache=1, also tried with "#inject"
TYPO3 now requires to configure dependency injection. It does not work automatically any more. Basically you need to add a special Configuration/Services.yaml file. See here how to configure it.

TYPO3 how to inject objectManager in hook?

Maybe it's just simple, but I can't figure it out.
TYPO3 8.7: I am programming a small hook: if a certain condition is met I want to send an email. Therefore I need the standalone view for the email template. But for the standalone view I need the object manager:
/** #var \TYPO3\CMS\Fluid\View\StandaloneView $emailView
$emailView = $this->objectManager->get('TYPO3\\CMS\\Fluid\\View\\StandaloneView');
At the beginning of my class I tried to inject the objectManager:
/**
* #var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
*/
protected $objectManager;
/**
* #param \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager
* #internal
*/
public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager)
{
$this->objectManager = $objectManager;
}
But it does not work: I run into an error: the objectManager is a null object. Which obviously means that the injection mechanism is not present in the hook.
How can this be achieved then?
Extbase Dependency Injection is not available in hooks, so you have to create instances of objects yourself.
$standaloneView = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class)
->get(TYPO3\CMS\Fluid\View\StandaloneView::class);

How do I include or autoload external libraries in a TYPO3 Extbase Extension? + Dependecy Injection?

I'm developing a TYPO3 4.6 Extension with Extbase 1.4 and im trying to include an external library. The library, in my case the facebook PHP SDK, is under $_EXTKEY/Resources/PHP/facebook-php-sdk/facebook.php. I would like the library to autoload and automatically inject (Dependecy Injection) where I need it.
Some comments I found online suggest that one should include libraries with require_once():
http://forge.typo3.org/issues/33142
if it's just a tiny helper library, it's intended to be stored in {PackageRoot}/Resources/PHP/{libraryName} and just included via require. is this suspected by the problem however?
if the FLOW3 package mainly represents the foreing library at all, like it's the case in Imagine or Swift package, the library code is put below {PackageRoot}/Classes directly."
http://lists.typo3.org/pipermail/typo3-project-typo3v4mvc/2011-July/009946.html
"I would include the class (using require_once) from within a specific action to handle this. That way you have access over those functions and the class becomes your library."
I tried this and it works like this:
<?php
require_once( t3lib_extMgm::extPath('extkey') . 'Resources/PHP/facebook-php-sdk/facebook.php');
class Tx_WsLogin_Domain_Repository_FacebookUserRepository extends Tx_WsLogin_Domain_Repository_UserRepository {
protected $facebook;
public function __construct() {
$this->setFacebook(new Facebook(array(
'appId' =>'',
'secret' => '')
));
parent::__construct();
}
public function setFacebook(Facebook $facebook) {
$this->facebook = $facebook;
}
public function sampleFunction() {
$userId = $this->facebook->getUser();
}
}
?>
But how can I get it to autoload and automatically inject the library with the injectFacebook function?
edit:
Like #alex_schnitzler and #sorenmalling mentioned about autoloading:
#PeterTheOne Put all the files inside ext_autoload.php and then use DI or the object manager.
#PeterTheOne put the class definition into ext_autoload.php in your extension?
I tried it like this (file: ext_autoload.php):
<?php
$extPath = t3lib_extMgm::extPath('extKey');
return array(
'facebook' => $extPath . 'Resources/PHP/facebook-php-sdk/facebook.php',
);
?>
It seems to find and include the right file. But when I try to user Dependency Injection (like peter answered) I get an error:
not a correct info array of constructor dependencies was passed!
InvalidArgumentException thrown in file /var/syscp/webs/web1/dev/typo3_src-4.5.15/typo3/sysext/extbase/Classes/Object/Container/Container.php in line 247.
I think this is because the constructor of the Facebook class has a required $config argument.
edit2:
I did what peter said in his answer and with the help of #alex_schnitzler and #sorenmalling, who pointed me to the ObjectManager, my FacebookService looks like this now:
class Tx_Extkey_Service_FacebookService implements t3lib_Singleton {
/**
* #var Tx_Extbase_Object_ObjectManagerInterface
*/
protected $objectManager;
/**
* Facebook from #link https://github.com/facebook/facebook-php-sdk facebook-php-sdk
*
* #var Facebook
*/
protected $facebook;
/**
* #param Tx_Extbase_Object_ObjectManagerInterface $objectManager
*/
public function injectObjectManager(Tx_Extbase_Object_ObjectManagerInterface $objectManager) {
$this->objectManager = $objectManager;
}
/**
*
*/
public function initializeObject() {
$this->facebook = $this->objectManager->create(
'Facebook',
array(
'appId' =>'input appId here',
'secret' => 'input app secret here'
)
);
}
/**
* #return Facebook
*/
public function getFacebook() {
return $this->facebook;
}
}
For more help read: http://forge.typo3.org/projects/typo3v4-mvc/wiki/Dependency_Injection_(DI) the parts about initializeObject() and Creating Prototype Objects through the Object Manager
First create ext_autoload.php in extension root folder
and add your code,it contain single dimension array with key as class name(class name must be prefix with extension key) and value as path to file.
make sure clear your site
<?php
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('rent_system');
return array(
'rent_system_TCPDF' => $extensionPath.'Resources/Private/PHP/tcpdf/tcpdf.php',
);
?>
In controller file
$pdf = $this->objectManager->create('rent_system_TCPDF');
Extbase injection is pretty simple. Here's the actual implementation. Using external libraries, however, is not.
Once you figure out how to load the library, have you tried just injecting it? Like so:
/**
* #var Facebook
*/
protected $facebook;
/**
* inject the facebook
*
* #param Facebook facebook
* #return void
*/
public function injectFacebook(Facebook $facebook) {
$this->facebook = $facebook;
}
NOTE: You need the #param in the comment and you also need to clear your configuration cache after adding this code.
I don't know about the Facebook SDK API, but hopefully you can instantiate the Facebook object with the default constructor and then add the arguments later with setter methods. You might want to create a FacebookService class (singleton) that loads the Facebook PHP and sets the essential arguments. Then you can inject a FacebookService to get the actual Facebook object whenever you need it.

can't turn of strict checking on include of duplicate constructor class - php 5.3

I have a system where Joomla and Symfony Frameworks work together. In a specific situation I need to include a range of files in Joomla from within Symfony. The problematic Joomla file has a "duplicate constructor" for PHP4 compatibility purposes, like so:
class JObject{
/**
* An array of errors
*
* #var array of error messages or JExceptions objects
* #access protected
* #since 1.0
*/
var $_errors = array();
/**
* A hack to support __construct() on PHP 4
*
* Hint: descendant classes have no PHP4 class_name() constructors,
* so this constructor gets called first and calls the top-layer __construct()
* which (if present) should call parent::__construct()
*
* #access public
* #return Object
* #since 1.5
*/
function JObject()
{
$args = func_get_args();
call_user_func_array(array(&$this, '__construct'), $args);
}
/**
* Class constructor, overridden in descendant classes.
*
* #access protected
* #since 1.5
*/
function __construct() {}
When I include this, I get an error
Strict Standards: Redefining already defined constructor
From what I can find on php.net I should be able to turn Strict standards off like this, but it doesn't work:
error_reporting(error_reporting() & (E_ALL ^ E_STRICT));
In your apps/<app name>/config/settings.yml you should be able to set the error_reporting level. Something like:
all:
.settings:
error_reporting: <?php echo (E_ALL | E_STRICT)."\n" ?>

Resources