When I tried to insert post data in dynamodb-local, following issue happened.
I'd like to know what’s the cause.
Version
Laravel: 9.48.0
Issue
Unresolvable dependency resolving [Parameter #0 [ array $args ]] in class Aws\AwsClient
It looks the cause is in constructor since the issue happened when I wrote DynamoDbClient $client as an argument in it.
My code
<?php
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Aws\DynamoDb\DynamoDbClient;
use Aws\DynamoDb\Marshaler;
use Aws\Sdk;
class ReplyKeywordsController extends Controller
{
/**
* #var Marshaler
*/
private $marshaler;
/**
* #var DynamoDbClient
*/
private $client;
/**
* DynamoModel constructor
* #param DynamoDbClient $client
* #param Marshaler $marshaler
*/
public function __construct(DynamoDbClient $client, Marshaler $marshaler)
{
$this->client = $client;
$this->marshaler = $marshaler;
}
public function store(Request $request)
{
$replyKeyword = $request->all();
$replyKeyword = $this->marshaler->marshalItem($request->all());
$dynamoParameters = [
"TableName" => "keywords",
"Key" => $replyKeyword
];
$this->client->putItem($dynamoParameters);
return redirect("reply_keyword");
}
}
Cleared cache based on below, but didn’t work.
Unresolvable dependency resolving [Parameter #0 [ <required> $name ]]
I kindly ask for your cooperation.
Thank you.
Thanks to Mr./M(r)s matiaslauriti, I solved the issue.
App/Providers/DynamoServiceProvider.php
<?php
declare(strict_types=1);
namespace App\Providers;
use Aws\DynamoDb\DynamoDbClient;
use Aws\Sdk;
use Illuminate\Support\ServiceProvider;
class DynamoServiceProvider extends ServiceProvider
{
/**
* Dynamo AWS-SDK接続
*/
public function register()
{
$this->app->singleton(DynamoDbClient::class, function () {
$awsSdk = new Sdk([
'credentials' => [
'key' => env('AWS_DYNAMO_KEY'),
'secret' => env('AWS_DYNAMO_SECRET'),
],
'endpoint' => env('AWS_DYNAMO_ENDPOINT'),
'region' => env('AWS_DYNAMO_REGION'),
'version' => env('AWS_DYNAMO_VERSION')
]);
return $awsSdk->createDynamoDb();
});
}
}
config/app.php
"providers" => {
App\Providers\DynamoServiceProvider::class,
}
Then I can use DynamoDbClient as argument in constructor.
Thank you.
Related
i have this error when I have controller using RedisProvider. im already set RedisProvider in app.php. what i'm misssing to make RedisProvider works? also this is just an example, the actual code even not using Redis, im trying to understand how service container and service provider works
app/Http/Controllers/MyController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Providers\RedisProvider;
class MyController extends Controller
{
//
public function Index(RedisProvider $redis) {
$redis->set("TEST","AKARAPACI 2550505");
}
}
app/Providers/RedisProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Redis\RedisLib;
class RedisProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->singleton(RedisLib::class, function ($app) {
return new RedisLib();
});
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
app/Redis/RedisLib
<?php
namespace App\Redis;
use Redis;
class RedisLib {
public $redis;
public function __construct() {
$this->redis = new redis();
$this->redisConnectionStatus = $this->redis->pconnect("192.168.7.147", 6379);
if($this->redisConnectionStatus) {
echo "REDIS_CONNECTED\n";
} else {
echo "ERR_CONNECT";
}
}
}
/config/app.php (only portion)
'providers' => [
//<...existing provider not included here-->
App\Providers\RedisProvider::class,
],
error Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Support\ServiceProvider is occured on line 52 of index.php, im using Laravel 9
...
51 $response = $kernel->handle(
52 $request = Request::capture()
53 )->send();
...
I got a problem when I call my entity Offer
I would like to call the method getApplication() but I got this error
Unable to guess how to get a Doctrine instance from the request information for parameter "offer".
Someone know how to call entity ? thanks
<?php
namespace App\Controller;
use App\Entity\Application;
use App\Entity\Offer;
use App\Repository\ApplicationRepository;
use App\Repository\BrandRepository;
use App\Repository\OfferRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class OfferController
* #package App\Controller
*
* #Route("/offer", name="offer_")
*/
class OfferController extends AbstractController
{
/**
* #Route("/", name="index")
*/
public function index(ApplicationRepository $applicationRepository, OfferRepository $offerRepository, Offer $offer)
{
$user = $this->getUser();
$offers = $offerRepository->findBy([], ['dateCreation' => 'DESC']);
$application = $applicationRepository->findOneBy(['id' => $offer->getApplication()]);
return $this->render('offer/index.html.twig', [
'offers' => $offers,
'application' => $application,
'offer' => $offer
]);
}
}
If your entity has a property named id that uniquely identifies an Offer, you could leverage param converter and simply add the {id} parameter to your URL. More info here.
<?php
namespace App\Controller;
use App\Entity\Application;
use App\Entity\Offer;
use App\Repository\ApplicationRepository;
use App\Repository\BrandRepository;
use App\Repository\OfferRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* Class OfferController
* #package App\Controller
*
* #Route("/offer", name="offer_")
*/
class OfferController extends AbstractController
{
/**
* #Route("/{id}", name="index")
*/
public function index(ApplicationRepository $applicationRepository, OfferRepository $offerRepository, Offer $offer)
{
$user = $this->getUser();
$offers = $offerRepository->findBy([], ['dateCreation' => 'DESC']);
$application = $applicationRepository->findOneBy(['id' => $offer->getApplication()]);
return $this->render('offer/index.html.twig', [
'offers' => $offers,
'application' => $application,
'offer' => $offer
]);
}
}
I have created AlbumControllerFactory.php in folder \module\Album\src\Album\Factory as follows: But it is showing error a mentioned above
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Album\Controller\AlbumController;
class AlbumControllerFactory implements FactoryInterface
{
/**
*
* #param ContainerInterface $container
* #param string $requestedName
* #param null|array $options
* #return AlbumController
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$class = $requestedName ? $requestedName : AlbumController::class;
$albumTable = $container->get('Album\Model\AlbumTable'); // get service from service manager
$controller = new $class($albumTable);
return $controller;
}
/**
* Provided for backwards compatibility; proxies to __invoke().
*
* #param ContainerInterface|ServiceLocatorInterface $container
* #return AlbumController
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, AlbumController::class);
}
}
And in my controller i have following code to get my factory:
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album;
use Album\Form\AlbumForm;
class AlbumController extends AbstractActionController
{
protected $_albumTable;
public function __construct(AlbumTable $albumTable)
{
$this->_albumTable = $albumTable;
}
public function indexAction()
{
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
}
And in my module.config.php i have set the controller as like follows:
return array(
'controllers' => array(
'factories' => array(
Controller\AlbumController::class => Factory\Controller\AlbumControllerFactory::class,
),
),
So How i can fix this issue in-order to make my module work fine as it was working fine before creating the factory but it was showing a deprecated message. Please have a look at let me know what wrong i have done and how to fix this.
Here is a full example of how to use factories in Zend 2/3. I guess you are missing namespace in module.config.php file, but please compare your namespaces and directories with these.
You should have following directory structure:
module
- Album
- config
module.config.php
- src
- Controller
AlbumController.php
- Factory
- Controller
AlbumControllerFactory.php
- Module.php
Factory
namespace Album\Factory\Controller
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Album\Controller\AlbumController;
class AlbumControllerFactory implements FactoryInterface
{
/**
*
* #param ContainerInterface $container
* #param string $requestedName
* #param null|array $options
* #return AlbumController
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$class = $requestedName ? $requestedName : AlbumController::class;
$albumTable = $container->get('Album\Model\AlbumTable'); // get service from service manager
$controller = new $class($albumTable);
return $controller;
}
/**
* Provided for backwards compatibility; proxies to __invoke().
*
* #param ContainerInterface|ServiceLocatorInterface $container
* #return AlbumController
*/
public function createService(ServiceLocatorInterface $container)
{
return $this($container, AlbumController::class);
}
}
Controller
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Album\Model\Album;
use Album\Form\AlbumForm;
class AlbumController extends AbstractActionController
{
protected $_albumTable;
public function __construct(AlbumTable $albumTable)
{
$this->_albumTable = $albumTable;
}
public function indexAction()
{
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
}
module.config.php
namespace Album;
use Album\Controller;
use Album\Factory;
return array(
'controllers' => array(
'factories' => array(
Controller\AlbumController::class => Factory\Controller\AlbumControllerFactory::class,
),
),
I like to have segregated factories, but you can keep all your factories in main Factory directory, but be sure to set correct namespaces for them and in module.config.php file
Your problem is about Namespace :
You said :
I have created AlbumControllerFactory.php in folder
\module\Album\src\Album\Factory
BUT you call
Controller\AlbumController::class => Factory\Controller\AlbumControllerFactory::class,
Factory\Controller\AlbumControllerFactory is not a correct Full Qualified Class Name (FQCN)
You should have this in your config file
Suppose your namespace declared in the config file is Album :
Controller\AlbumController::class => Factory\AlbumControllerFactory::class
I'm getting this error:
BindingResolutionException in compiled.php line 1029:
Target [App\Models\Contracts\Repositories\IUserRepository] is not instantiable.
My code is as follows:
Interface:
namespace App\Models\Contracts\Repositories;
use App\Models\Objects\DTO\User;
interface IUserRepository
{
function Create( User $user );
}
Concrete:
namespace App\Models\Concrete\Eloquent;
use App\Models\Contracts\Repositories\IUserRepository;
use App\Models\Objects\DTO\User;
class EqUserRepository implements IUserRepository
{
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
public function Create( User $user )
{
return User::create( [
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'username' => $user->username,
'email' => $user->email,
'password' => bcrypt( $user->password ),
] );
}
}
Service Provider:
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* This service provider is a great spot to register your various container
* bindings with the application. As you can see, we are registering our
* "Registrar" implementation here. You can add your own bindings too!
*
* #return void
*/
public function register()
{
$this->app->bind(
'App\Models\Contracts\Repositories\IUserRepository',
'App\Models\Concrete\Eloquent\EqUserRepository'
);
}
}
Controller:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use App\Models\Contracts\Repositories\IUserRepository;
use App\Models\Objects\DTO\User;
class AuthController extends Controller
{
protected $auth;
private $userRepository;
public function __Construct(
Guard $auth,
IUserRepository $userRepo )
{
...
Folder structure
I have also seen that I may need to declare the namespaces in my composer.json, So i have tried the following as well as just the above:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/",
"App\\Models\\Concrete\\Eloquent\\": "app/Models/Concrete/Eloquent/",
"App\\Models\\Contracts\\Repositories\\": "app/Models/Contracts/Repositories/",
"App\\Models\\Objects\\DTO\\": "app/Models/Objects/DTO/"
}
},
and then ran composer dump-autoload
Any ideas what I am forgetting to do?
I noticed the compiled.php was not being updated.
Run this function in cmd line on the root folder of your project:
php artisan clear-compiled
If you also run in below error :
BindingResolutionException in Container.php line 749: Target
[App\Contracts\TestContract] is not instantiable.
Clear your config cache with :
php artisan config:clear
I had same error solved by adding repository in app/providers/AppServiceProvider in register method like the below.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->register(RepositoryServiceProvider::class); // here
}
}
I went to override WordpressResourceOwner into HWIOAuthBundle as it didn`t return user information response
I notice that every ResourceOwner work as Service and declared into oauth.xml
i had override registration twig into HWIOAuthBundle and create new bundle inherit from HWIOAuthBundle like answer of this question but I can`t work the same with WordpressResourceOwner
after searching I had found we can override class of WordpressResourceOwner Service
Steps:
1) create new ResourceOwner
EX:
namespace project\OAuthBundle\OAuth\ResourceOwner;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner;
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
/**
* Override WordpressResourceOwner class into HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\WordpressResourceOwner
*
* #author ahmedhamdy
*
*/
class WordpressResourceOwner extends GenericOAuth2ResourceOwner
{
/**
* {#inheritDoc}
*/
protected $paths = array(
'identifier' => 'ID',
'nickname' => 'username',
'realname' => 'display_name',
'email' => 'email',
'profilepicture' => 'avatar_URL',
);
/**
* {#inheritDoc}
*/
protected function doGetUserInformationRequest($url, array $parameters = array())
{
$apiAccessToken = $parameters['apiAccessToken'];
$headers = array(
0 => 'authorization: Bearer '.$apiAccessToken,
);
return $this->httpRequest($url,null,$headers);
}
/**
* {#inheritDoc}
*/
public function getUserInformation(array $accessToken, array $extraParameters = array())
{
$url = $this->normalizeUrl($this->options['infos_url'], array(
'access_token' => $accessToken['access_token']
));
$parameters = array(
'apiAccessToken' => $accessToken['access_token'],
);
$content = $this->doGetUserInformationRequest($url,$parameters)->getContent();
$response = $this->getUserResponse();
$response->setResponse($content);
$response->setResourceOwner($this);
$response->setOAuthToken(new OAuthToken($accessToken));
return $response;
}
/**
* {#inheritDoc}
*/
protected function configureOptions(OptionsResolverInterface $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'authorization_url' => 'https://public-api.wordpress.com/oauth2/authorize',
'access_token_url' => 'https://public-api.wordpress.com/oauth2/token',
'infos_url' => 'https://public-api.wordpress.com/rest/v1/me',
));
}
}
2) create CompilerPass class to override service class like Symfony2 documentation
EX:
namespace project\OAuthBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* OverrideWordpressResourceOwner
*
* #author ahmedhamdy
*/
class OverrideWordpressResourceOwner implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition("hwi_oauth.abstract_resource_owner.wordpress");
$definition->setClass('ProfileTree\OAuthBundle\OAuth\ResourceOwner\WordpressResourceOwner');
}
}
3) we must override build method into Bundle class like Symfony2 documentation
EX:
namespace Project\OAuthBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use ProfileTree\OAuthBundle\DependencyInjection\Compiler\OverrideWordpressResourceOwner;
class ProfileTreeOAuthBundle extends Bundle
{
public function getParent()
{
return 'HWIOAuthBundle';
}
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new OverrideWordpressResourceOwner());
}
}
4) last step calling compile method for ContainerBuilder into Bundle Extension like Symfony2 documentation
EX:
namespace Project\OAuthBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {#link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class ProfileTreeOAuthExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
$container->compile();
}
}