Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel use non-laravel composer package in controller

I'm trying to use a non-laravel composer package in a Laravel controller. I've added the project to the composer.json file like so:

"require": {
    "laravel/framework": "5.0.*",
    "php": ">=5.4.0",
    "abraham/twitteroauth": "0.5.2"
},

I then ran:

composer update

Within the project, which has installed the package in the vendor/ directory as expected, and I see it there. However, when adding the following code to the controller:

<?php
namespace App\Http\Controllers;

class HomeController extends Controller {

    use Abraham\TwitterOAuth\TwitterOAuth;

public function index()
{
    $o = new TwitterOauth();
    return view('home');
}

Laravel returns the following error:

Trait 'App\Http\Controllers\Abraham\TwitterOAuth\TwitterOAuth' not found

I suspect this has something to do with the fact that the namespace is already declared, but I don't know enough about PHP namespaces to resolve the issue.

Any help would be welcome!

like image 401
BnMcG Avatar asked Mar 19 '15 20:03

BnMcG


1 Answers

Your controller file is in the App\Http\Controllers namespace

namespace App\Http\Controllers;

You attempted to add a trait to your controller using a relative class/trait name

use Abraham\TwitterOAuth\TwitterOAuth;

If you use a relative trait name, PHP will assume you want trait in the current namespace, which is why it complains about

App\Http\Controllers\Abraham\TwitterOAuth\TwitterOAuth

or

App\Http\Controllers\
combined with
Abraham\TwitterOAuth\TwitterOAuth

Try using an absolute trait name, and you should be fine

use \Abraham\TwitterOAuth\TwitterOAuth;

Or, import the TwitterOAuth into the current namespace

namespace App\Http\Controllers;
use Abraham\TwitterOAuth\TwitterOAuth;

And then use with the short name

class HomeController extends Controller {

    use TwitterOAuth;
}

Update:

OK, we get to blame PHP's double use of use here. In your class definition, you said

class HomeController extends Controller {

    use Abraham\TwitterOAuth\TwitterOAuth;

    public function index()
    {
        $o = new TwitterOauth();
        return view('home');
    }
}

When you use use inside a class, PHP interprets that as "apply this trait to this class". I'm not familiar with the library, so I assumed that Abraham\TwitterOAuth\TwitterOAuth is a trait. It's not.

When you use use outside of a class definition, you're telling PHP to to "use this class in this namespace without a namespace prefix". If you remove the use statement from your class

class HomeController extends Controller {

    //use Abraham\TwitterOAuth\TwitterOAuth;
}

and place it outside, under the namespace keyword

namespace App\Http\Controllers;
use Abraham\TwitterOAuth\TwitterOAuth;

You should be able to use the class TwitterOAuth to instantiate your objects.

like image 133
Alan Storm Avatar answered Oct 06 '22 00:10

Alan Storm