Using a non-laravel package on Laravel 4 - php

Is it possible to include a package that was not specifically designed for L4 in the framework?
If so, how is it done? I know I need to add the package to my composer.json which adds it to the vendor folder, but can I register it somehow in the providers array? are there any other steps necessary?
I would like to use the Google checkout package originally designed for Yii

Using third party composer packages with Laravel 4
When developers create composer packages, they should map the auto-loading using PSR-0 or PSR-4 standards. If this is not the case there can be issues loading the package in your Laravel application. The PSR-0 standard is:
{
"autoload": {
"psr-0": { "Acme": "src/" }
}
}
And the PSR-4 standard:
{
"autoload": {
"psr-4": { "Acme\\": "src/" }
}
}
Basically the above is a standard for telling composer where to look for name-spaced files. If you are not using your own namespaces you dont have to configure anything else.
SCENARIO 1
PSR-0 standard following packages (with autoload classmap) in Laravel
This is a simple one, and for example i will use the facebook php sdk, that can be found:
https://packagist.org/packages/facebook/php-sdk
Step 1:
Include the package in your composer.json file.
"require": {
"laravel/framework": "4.0.*",
"facebook/php-sdk": "dev-master"
}
Step 2:
run: composer update
Step 3:
Because the facebook package uses a class map its working out of the box, you can start using the package instantly. (The code example below comes straight from a normal view. Please keep your logic out from views in your production app.)
$facebook = new Facebook(array(
'appId' => 'secret',
'secret' => 'secret'
));
var_dump($facebook); // It works!
SCENARIO 2
For this example i will use a wrapper from the instagram php api. Here there need to be made some tweaks to get the package loaded. Lets give it a try!
The package can be found here:
https://packagist.org/packages/fishmarket/instaphp
Step 1:
Add to composer .json
"require": {
"laravel/framework": "4.0.*",
"fishmarket/instaphp": "dev-master"
}
Then you can update normally (composer update)
Next try to use the package like you did with the facebook package. Again, this is just code in a view.
$instagramconfig = array(
'client_id' => 'secret',
'client_secret'=> 'secret',
'access_token' => 'secret'
);
$api = Instaphp::Instance(null, $instagramconfig);
var_dump($api); // Epic fail!
If you try the above example you will get this error:
FatalErrorException: Error: Class 'Instaphp' not found in ...
So we need to fix this issue. To do this we can examine the instagram composer.json, that has its autoload diffrent than the facebook php sdk had.
"autoload": {
"psr-0": { "Instaphp": "." }
}
Compared to the facebook composer.json:
"autoload": {
"classmap": ["src"]
}
(Composer handles different kinds of autoloading, from files and class-maps to PSR. Take a look at your vendor/composer/ folder to see how its done.)
Now we will have to load the class, manually. Its easy, just add this (top of your controller, model or view):
use Instaphp\Instaphp;
composer dump-autoload, and it works!
step2 (optional)
Another method is (if you dont want to use the "use" statement, you can simply tell composer to look for the files straight from your code. Just change the Instance like so:
// reference the name-spaced class straight in the code
$api = Instaphp\Instaphp::Instance(null, $instagramconfig);
var_dump($api); // It works
However I suggest using the usestatement to make it clear to other developers (and your future self) what (external) classes/packages are used in the program.
SCENARIO 3
Here we use the Laravels built in IOC container to register service providers. Please note that some packages might not be suitable for this method. I will use the same Instagram package as in scenario 2.
Quick and dirty
If you don't care about design patterns and service providers you can bind a class like this:
App::bind('Instaphp', function($app)
{
return new Instaphp\Instaphp;
});
And you resolve it like this.
App::make('Instaphp');
Quick and dirty end
If you're working on a bigger project, and you make use of interfaces you should probably abstract the bindings further.
Step 1:
Create a folder inside your app folder, for example a 'providers' folder.
app/providers
Make sure Laravel auto-loads that folder, you can pass in some additional info to composer.json, like this:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/providers" // this was added
]
},
Now create a File inside the new folder called Instagram.php and place this inside:
<?php
use Illuminate\Support\ServiceProvider;
class InstagramServiceProvider extends ServiceProvider {
public function register()
{
$this->app->bind('Instaphp', function()
{
return new Instaphp\Instaphp;
});
}
}
Now run composer dump-autoload again, and you can use the package. Note that the instagram package has a final private function __construct(), this means you cannot use that package outside the original class without changing the construct method to public. I'm not saying this is a good practice, and i suggest to use the scenario 2, in the case of the instagram package.
Anyway, after this you can use the package like this:
$instagramInstance = App::make('Instaphp');
$instagramconfig = array(
'client_id' => 'secret',
'client_secret'=> 'secret',
'access_token' => 'secret'
);
$instagram = new $instagramInstance();
$userfeed = $instagram->Users->feed($instagramconfig);
var_dump($userfeed); // It works!

Add "tvr/googlecheckout": "dev-master" this to your composer.json.
Run composer install, then you can use the IoC container. Some code examples can be found in the official docs for Laravel 4: http://four.laravel.com/docs/ioc#basic-usage

Related

Class not found error with composer autoload

I must be making a simple error, I have not used Composer before now. I have followed the instructions on the GitHub page, but I'm getting a Class 'ZCRMRestClient' not found error when I load the page.
composer.json:
{
"require": {
"zohocrm/php-sdk": "^2.0"
}
}
PHP is
require 'vendor/autoload.php';
$configuration = array(
'client_id' => '1000.***',
'client_secret' => '***',
'redirect_uri' => '***',
'currentUserEmail' => '***',
);
ZCRMRestClient::initialize($configuration);
$contacts = ZCRMRestClient::getModule(“Contacts”);
echo "<pre>\n";
print_r($contacts);
echo "\n</pre>";
I've tried \ZCRMRestClient::initialize($configuration) but that hasn't helped.
There is new sdk 3.0 available, and the old sdk 2.0 is moved to:
"require": {
"zohocrm/php-sdk-archive": "^2.0"
}
I'm going to assume you've executed the composer require zohocrm/php-sdk command, or potentially added the requirement straight into your project's composer.json by hand.
Make sure you're importing the correct namespace for the library - in this case it seems to be zcrmsdk\crm\setup\restclient\ZCRMRestClient
You should write use zcrmsdk\crm\setup\restclient\ZCRMRestClient; at the top of the file then invoke methods as you currently do.
Alternatively, you can invoke methods as in the following example: \zcrmsdk\crm\setup\restclient\ZCRMRestClient::initialize($configuration);
After that the most likely problem is that your autoload file doesn't contain a reference to your library.
composer dump-autoload should fix that (from the command line.)
And finally perhaps you are not requiring the vendor folder correctly!

How can I use a class from vendor folder in laravel project

I am trying to include guzzle http client from a vendor folder and using composer. Here is what I have tried so far.
Location of guzzle http client file vendor/guzzle/guzzle/src/Guzzle/Http/Client.php
In composer.json file I included
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"files":["vendor/guzzle/guzzle/src/Guzzle/Http/Client.php"],
"psr-4": {
"App\\": "app/"
}
},
The I ran the command composer dumpautoload.
In my controller I am trying to call an api end point like this
use GuzzleHttp\Client;
$client = new Client(); // this line gives error
$res = $client->get('https://api.fixer.io/latest?symbols=CZK,EURO');
The error is Class 'GuzzleHttp\Client' not found
What I am missing here, please help me. Thanks.
For a better file structure here is a screenshot of of the file location
Short Version: You're trying to instantiate a class that doesn't exist. Instantiate the right class and you'll be all set.
Long Version: You shouldn't need to do anything fancy with your composer.json to get Guzzle working. Guzzle adheres to a the PSR standard for autoloading, which means so long as Guzzle's pulled in via composer, you can instantiate Guzzle classes without worrying about autoloading.
Based on the file path you mentioned, it sounds like you're using Guzzle 3. Looking specifically at the class you're trying to include
namespace Guzzle\Http;
/*...*/
class Client extends AbstractHasDispatcher implements ClientInterface
{
/*...*/
}
The guzzle client class in Guzzle 3 is not GuzzleHttp\Client. Its name is Guzzle\Http\Client. So try either
$client = new \Guzzle\Http\Client;
or
use Guzzle\Http\Client;
$client = new Client;
and you should be all set.

How to load bundles in a Symfony console component-based application?

I am probably having some fundamental issue with understanding the Symfony Console component. I am trying to write a console-based application and I wanted to add the Doctrine bundle to it to create ORM-based entities, however, I am not able to load the bundle into my application.
What I found is that I should create app/AppKernel.php and add the bundle there:
public function registerBundles()
{
$bundles = array(
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
);
return $bundles;
}
I have then also added the AppKernel to the composer.json and dumped composer's autoload files:
"classmap": [ "app/AppKernel.php" ]
However, I am still unable to see any Doctrine commands in my console application's entry point. I don't even think the Kernel is loaded properly, the most confusing part to me is the difference between these two files on Github. First you have the Console component's Application.php which uses strings for its constructor parameters:
https://github.com/symfony/console/blob/master/Application.php
And then there's the same file in the Symfony Framework and that one uses the Kernel as a parameter:
https://github.com/symfony/framework-bundle/blob/master/Console/Application.php
So am I completely on the wrong path here? How do I load bundles / Kernels in a Console Component application? Or do I need the full Symfony package to do this sort of thing? That would seem kind of overkill if I just needed to write a somewhat complex terminal application.
Just in case it is any use, these are the relevant packages in my composer.json:
"symfony/console": "v3.3.*",
"symfony/yaml": "v3.3.*",
"doctrine/orm": "~2.5",
"doctrine/doctrine-bundle": "~1.6",
"doctrine/doctrine-cache-bundle": "~1.2",
If you create a console command which extends the ContainerAwareCommand as described here:
https://symfony.com/doc/current/console.html#getting-services-from-the-service-container
Then you can call:
$em = $this->container->get('doctrine.orm.entity_manager');
Which gives you the EntityManager allowing you to use Doctrine in your command line application. There is no need to edit your AppKernel or composer file to get Doctrine working.

Class 'AWeberAPI' not found

I got no clue why AWeberAPI is not found. Any help is appreciated.
php code:
require('vendor/autoload.php');
new PHPExcel;
new AWeberAPI;
composer.json:
{
"require": {
"aweber/aweber": "^1.1",
"phpoffice/phpexcel": "^1.8"
}
}
The problem
The module doesn't appear to be properly configured for use/autoloading with composer. They may have just added the composer configuration to allow you to easily install it, but not to use it within the composer autoloader.
The generic convention for it is that AWeberAPI should match the package's PSR-4 autoloader format, which says "look in aweber_api", then it will look for a class named AWeberAPI.php. You can test this behaviour is correct by adding this file:
<?php
// File: vendor/aweber/aweber/aweber_api/AWeberAPI.php
class AWeberAPI {
public function __construct() {
die('yeah, it works now...');
}
}
Then try your script again, the class will exist now.
What can I do?
Well - you could submit a pull request to their repository to fix it, but it looks like it would involve renaming the classes and filenames which would be a breaking change so I probably wouldn't bother.
You can get it to work by requiring the actual source of the API library instead of the composer autoloader in this case:
require_once 'vendor/aweber/aweber/aweber_api/aweber_api.php';

Removing or renaming swift in laravel

The error I am getting is
file: "/var/www/html/goalline/swiftmailer333/Swift.php" line: 32
message: "Cannot redeclare class Swift" type:
"Symfony\Component\Debug\Exception\FatalErrorException"
I have a need to remove Swift from Laravel as it conflicts with functions form a legacy application that my Laravel app needs to call.
How can I do this? Whether I should is irrelevant I have to use those functions from the legacy application.
I've tried commenting
'Mail' => 'Illuminate\Support\Facades\Mail',
and 'Illuminate\Mail\MailServiceProvider' but that didn't work.
You'll have to namespace your Swift class:
<?php
namespace YourApp;
class Swift {
}
Then use it this way:
$swift = new YourApp\Swift;
Another possibility is to create a nasty hack to remove it from your Laravel installation, but to do that you'll have to create a repository of your own and use your repository in your composer.json file:
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/yourusername/swiftmailer"
}
],
"require": {
"swiftmailer/swiftmailer": "dev-master"
}
}
Your repository can pretty much be a copy of swiftmailer's which you basically remove every file except the composer.json.

Categories