Method get not found - php

I create my own ServiceProvider to send param form ENV when initiation class:
class InstagramServiceProvider extends ServiceProvider
{
protected $defer = true;
public function boot()
{
$this->publishes([
__DIR__.'/../config/config.php' => config_path('instagram.php'),
]);
}
public function register()
{
$this->app->bind('instagram.client', function ($app) {
return new InstagramClient([
'apiKey' => $app['config']->get('instagram.clientId'),
'apiSecret' => $app['config']->get('instagram.clientSecret'),
'apiCallback' => $app['config']->get('instagram.redirectUri'),
'scope' => $app['config']->get('instagram.scope'),
]);
});
}
public function provides()
{
return array('instagram.client');
}
}
And I can't get data from config? What I do wrong?

Laravel has a function built specifically for this job called config(). You can use it as follows:
public function register()
{
$this->app->bind('instagram.client', function ($app) {
return new InstagramClient([
'apiKey' => config('instagram.clientId'),
'apiSecret' => config('instagram.clientSecret'),
'apiCallback' => config('instagram.redirectUri'),
'scope' => config('instagram.scope'),
]);
});
}
Alternatively you could use a bracket notation like so:
$app['config']['instagram']['clientId']
For more information see documentation: https://laravel.com/docs/5.4/configuration#accessing-configuration-values

Related

Fatal error: Call to a member function get() on null in Zend Framework 2

I am getting null when using $sm=$this->getServiceLocator() as a result $sm->get("XXXXXXXXXXX") throwing a Fatal error: Call to a member function get() on null.
What i am doing is that, while receiving user data in controller i am calling another controller validatorController inside my requested controller which is signupController and in validatorController i am using $sm=$this->getServiceLocator() which gives the above error
Here is my work
Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php
Module.php
<?php
namespace User;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\ResultSet\ResultSet;
use User\Controller\ValidatorController;
use User\Model\User;
use User\Model\UserTable;
class Module {
public function getConfig() {
return include __DIR__."/config/module.config.php";
}
public function getAutoloaderConfig() {
return array(
"Zend\loader\StandardAutoloader"=>array(
"namespaces"=>array(
__NAMESPACE__=>__DIR__."/src/".__NAMESPACE__
)
)
);
}
public function getServiceConfig() {
return array(
"factories"=>array(
'User\ValidatorController' => function ($sm) {
$validatorController = new ValidatorController();
return $validatorController;
},
"User\Model\UserTable"=>function($sm) {
$tableGateway=$sm->get("UserTableGateway");
$table=new UserTable($tableGateway);
return $table;
},
"UserTableGateway"=>function($sm) {
$dbAdapter=$sm->get("Zend\Db\Adapter\Adapter");
$resultSetPrototype=new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway("users",$dbAdapter,null,$resultSetPrototype);
}
)
);
}
}
module.config.php
<?php
return array(
"controllers"=>array(
"invokables"=>array(
"User\Controller\User"=>"User\Controller\UserController",
'User\Controller\Signup' => 'User\Controller\SignupController',
'User\Controller\Validator' => 'User\Controller\ValidatorController'
)
),
// The following section is new and should be added to your file
"router"=>array(
"routes"=>array(
"user"=>array(
"type"=>"segment",
"options"=>array(
"route" => "/user[/:action][/:id]",
"constraints" => array(
"id" => "[0-9]+",
),
"defaults"=>array(
"controller"=>"User\Controller\User"
)
)
),
'signup' => array(
'type' => 'segment',
'options' => array(
'route' => '/signup',
'defaults' => array(
'controller' => 'User\Controller\Signup',
)
)
),
)
),
'view_manager' => array(//Add this config
'strategies' => array(
'ViewJsonStrategy',
),
),
);
SignupController.php
<?php
namespace User\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;
class SignupController extends AbstractRestfulController{
private $_userTable;
public function create($data) {
/*
* The above error is not coming here
* $check=$this->_getUserTable()->isUnique($data['email']);
*
* But inside the below controller
*/
// Calling a validatorContoller
$validator=$this->getServiceLocator()->get('User\ValidatorController');
$response=$validator->validateEmail($data['email']);
return new JsonModel($response);
}
public function _getUserTable() {
if(!$this->_userTable) {
$sm=$this->getServiceLocator();
$this->_userTable=$sm->get("User\Model\UserTable");
}
return $this->_userTable;
}
}
ValidatorController.php
<?php
namespace User\Controller;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\Validator\EmailAddress;
class ValidatorController extends AbstractRestfulController {
private $_userTable;
public function validateEmail($email) {
$validator = new EmailAddress();
if($validator->isValid($email)) {
// check if it is a unique entry in user table
// ***(THE SOURCE OF ERROR IS HERE)***
$check=$this->_getUserTable()->isUnique($email);
return $check;
}
}
public function _getUserTable() {
if(!$this->_userTable) {
$sm=$this->getServiceLocator();
$this->_userTable=$sm->get("User\Model\UserTable");
}
return $this->_userTable;
}
}
NOTE
Error comes when i use $check=$this->_getUserTable()->isUnique($email); in ValidatorController.php but not in SignupController.php
Thankyou
getServiceLocator() is deprecated in ZendFramework 2. You must inject _userTable in your ValidatorController from your Module.php like this :
class Module {
...
public function getServiceConfig() {
return array(
"factories"=>array(
'User\ValidatorController' => function ($sm) {
$userTable = $sm->get("User\Model\UserTable");
$validatorController = new ValidatorController();
$validatorController->setUserTable($userTable);
return $validatorController;
},
...
}
Then add a setUserTable() method in your ValidController and modify the getUserTable() method :
class ValidController {
public function setUserTable($suerTable) {
$this->_suerTable = $userTable
}
public function _getUserTable() {
return $this->_userTable;
}
}

Laravel Fractal transformer, how to pass and get extra variable

I'm using Dingo API to create an API in Laravel 5.2 and have a controller returning data with
return $this->response->paginator($rows, new SymptomTransformer, ['user_id' => $user_id]);
However, I don't know how to retrieve user_id value in the SymptomTransformer! Tried many different ways and tried looking into the class but I'm relatively new to both Laravel and OOP so if anyone can point me to the right direction, it'd be greatly appreciated.
Below is my transformer class.
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
You can pass extra parameter to transformer constructor.
class SymptomTransformer extends TransformerAbstract
{
protected $extra;
public function __construct($extra) {
$this->extra = $exta;
}
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->extra);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
And call like
return $this->response->paginator($rows, new SymptomTransformer(['user_id' => $user_id]));
You can set extra param via setter.
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->test_param);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
public function setTestParam($test_param)
{
$this->test_param = $test_param;
}
}
And then:
$symptomTransformer = new SymptomTransformer;
$symptomTransformer->setTestParam('something');
return $this->response->paginator($rows, $symptomTransformer);
If you are using Dependency Injection, then you need to pass params afterwards.
This is my strategy:
<?php
namespace App\Traits;
trait TransformerParams {
private $params;
public function addParam() {
$args = func_get_args();
if(is_array($args[0]))
{
$this->params = $args[0];
} else {
$this->params[$args[0]] = $args[1];
}
}
}
Then you implement the trait in your transformer:
<?php
namespace App\Transformers;
use App\Traits\TransformerParams;
use App\User;
use League\Fractal\TransformerAbstract;
class UserTransformer extends TransformerAbstract
{
use TransformerParams;
public function transform(User $user)
{
return array_merge([
'id' => (int) $user->id,
'username' => $user->username,
'email' => $user->email,
'role' => $user->roles[0],
'image' => $user->image
], $this->params); // in real world, you'd not be using array_merge
}
}
So, in your Controller, just do this:
public function index(Request $request, UserTransformer $transformer)
{
$transformer->addParam('has_extra_param', ':D');
// ... rest of the code
}
Basically, the trait is a bag for extra params.

Laravel call to member function create() on a non-object

I'm trying to seed a database using some model factories but I'm getting error call to member function create() on a non-object
Below are my model factories:
$factory->define(App\Organisation::class, function ($faker) {
return [
'name' => $faker->company,
];
});
$factory->define(App\Department::class, function ($faker) {
return [
'name' => $faker->catchPhrase,
'organisation_id' => factory(App\Organisation::class)->make()->id,
];
});
$factory->define(App\User::class, function ($faker) {
return [
'email' => $faker->email,
'password' => str_random(10),
'organisation_id' => factory(App\Organisation::class)->make()->id,
'remember_token' => str_random(10),
];
});
In my seeder I'm using the following to create 2 organizations and a associate a user and a department to each organization and then to make a user the manager of that department:
factory(App\Organisation::class, 2)
->create()
->each(function ($o)
{
$user = $o->users()->save(factory(App\User::class)->make());
$department = $o->departments()->save(factory(App\Department::class)->make());
$department->managedDepartment()->create([
'organisation_id' => $o->id,
'manager_id' => $user->id,
]);
});
However I'm getting fatalerrorexception call to member function create() on a non-object
I thought $department is an object?
My department model is as follows:
class Department extends Model
{
protected $fillable = ['name','organisation_id'];
public function organisation()
{
return $this->belongsTo('App\Organisation');
}
/* a department is managed by a user */
public function managedDepartment()
{
$this->hasOne('App\ManagedDepartment');
}
}
And my managedDepartment model is as follows:
class ManagedDepartment extends Model
{
protected $table = 'managed_departments';
protected $fillable = ['organisation_id', 'department_id', 'manager_id',];
public function department()
{
$this->belongsTo('App\Department');
}
public function manager()
{
return $this->belongsTo('App\User');
}
}
Can anyone help?
Try to return your relation
public function department()
{
return $this->belongsTo('App\Department');
}
And here
/* a department is managed by a user */
public function managedDepartment()
{
return $this->hasOne('App\ManagedDepartment');
}
I think it will resolve your problem.
Firstly, do not make foreign keys fillable!
Secondly, where is your organisation function in ManagedDepartment? You should create one, otherwise the following will not work, because association is not possible.
Thirdly, I think you should change make() to create() in the following
$factory->define(App\Organisation::class, function ($faker) {
return [
'name' => $faker->company,
];
});
$factory->define(App\Department::class, function ($faker) {
return [
'name' => $faker->catchPhrase,
'organisation_id' => factory(App\Organisation::class)->create()->id,
];
});
$factory->define(App\User::class, function ($faker) {
return [
'email' => $faker->email,
'password' => str_random(10),
'organisation_id' => factory(App\Organisation::class)->create()->id,
'remember_token' => str_random(10),
];
});
Furthermore:
factory(App\Organisation::class, 2)
->create()
->each(function ($o)
{
$user = factory(App\User::class)->create();
$o->users()->attach($user->id);
$department = factory(App\Department::class)->create();
$o->departments()->attach($department);
$managedDep = new ManagedDepartment();
$managedDep->associate($o);
$managedDep->associate($user);
$managedDep->associate($department);
$managedDep->save();
});

Integration of hybrid_auth in laravel 5

I am new to laravel framework any help would appreciate
When i try to execute the below code i get this error
FatalErrorException in SocialController.php line 27: Class 'App\Http\Controllers\Hybrid_Auth' not found in SocialController.php line 27
when i remove the namespace from SocialController.php i get this error saying BaseController not found.
onclick this button
<i class="fa fa-facebook"></i> Facebook
SocialController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class SocialController extends BaseController
{
//this is the code for facebook Login
public function getFacebookLogin($auth=NULL)
{
if ($auth == 'auth')
{
try
{
Hybrid_Endpoint::process();
}
catch (Exception $e)
{
return Redirect::to('fbauth');
}
return;
}
$oauth = new Hybrid_Auth(app_path(). '/config/fb_auth.php');
$provider = $oauth->authenticate('Facebook');
$profile = $provider->getUserProfile();
return var_dump($profile).'Log Out';
}
public function getLoggedOut()
{
$fauth = new Hybrid_auth(app_path().'/config/fb_auth.php');
$fauth->logoutAllProviders();
return view::make('/');
}
}
fb_auth.php
<?php
return array(
"base_url" => "http://urmk.com/fbauth/auth",
"providers" => array (
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "APP_ID", "secret" => "APP_SECRET" ),
"scope" => "email"
)
)
);
Routes.php
Route::get('fbauth/{auth?}' ,array('as'=>'facebook', 'uses'=>'SocialController#getFacebookLogin'));
Route::get('logout',array('as'=>'logout','uses'=>'SocialController#getLoggedOut'));
You will need to add the namespace to your Hybrid Auth class. At the moment, when you are trying to instantiate the Hybrid_Auth object, it's not finding the class definition.
Here is my setup for Laravel:
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind('Hybrid_Auth', function($app) {
return new \Hybrid_Auth(config_path('hybridauth.php'));
});
}
config/hybridauth.php
<?php
return [
'base_url' => env('APP_URL').'/auth/endpoint',
'providers' => [
'Facebook' => [
'enabled' => true,
'display' => 'popup',
'keys' => [
'id' => 'xxxx',
'secret' => 'xxx'
],
'scope' => 'email'
],
]
];
app/Http/routes.php
Route::group(['prefix' => 'auth'], function()
{
Route::get('login', 'AuthenticateController#login');
Route::get('endpoint', 'AuthenticateController#endpoint');
Route::get('logout', 'AuthenticateController#logout');
});
app/Http/Controllers/AuthenticateController.php
public function login(\Hybrid_Auth $auth)
{
$provider = $auth->authenticate('facebook');
$profile = $provider->getUserProfile();
$user = User::where('facebook', '=', $profile->identifier);
if($user->first()) {
return response()->json(['token' => $this->signin($user->first())]);
} else {
$user = new User;
$user->facebook = $profile->identifier;
$user->save();
return response()->json(['token' => $this->signin($user)]);
}
}
public function endpoint() {
\Hybrid_Endpoint::process();
}
public function logout(\Hybrid_Auth $auth) {
$auth->logoutAllProviders();
}

How to define your own list of invokables and access this from a AbstractFactory

I want to build my own list of invokables and access it from my AbstractFactory.
/**
* Get the service config
*/
public function getServiceConfig()
{
return array(
'invokables' => array(
),
'foo-invokables' => array(
'FooService' => 'Foo\Service\FooService',
)
);
}
The factory should then check this list to see the alias is within the list of foo-invokables.
public function canCreateServiceWithName(ServiceLocatorInterface $objServiceManager, $sCanonicalName, $sRequestedName) {
// TODO check if the $sRequestedName is contained with in the foo-invokables return true
}
Thanks in advance.
You can do it as simple as this:
class Module implements ConfigProviderInterface //...
{
//...
public function getConfig()
{
return [
'my_invokables' => [
'MyInvokables\Invokable1',
'MyInvokables\Invokable2',
]
];
}
//...
}
class AbstractMyInvokablesFactory implements AbstractFactoryInterface
{
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$config = $serviceLocator->get('config');
return in_array($requestedName, $config['my_invokables']);
}
//...
}

Categories