ActiveCampaign / activecampaign-api-php

MIT License
115 stars 76 forks source link

Laravel Install #50

Closed bobby5892 closed 8 years ago

bobby5892 commented 8 years ago

Hey guys, and thanks in advance.

I did the composer install.. No issue there.. But Laravel only allows classes to run in a provider/facade method, in their own namespace.

Do you have any laravel instructions?

pevans commented 8 years ago

Hey Bobby,

I'm afraid we don't have instructions specific to Laravel! Having said that, the ActiveCampaign class (and others here) are not in any declared namespace, so you should be able to reference them like new \ActiveCampaign(...) from within Laravel.

Let us know if you're still running into problems!

QWp6t commented 8 years ago

But Laravel only allows classes to run in a provider/facade method, in their own namespace.

That's incorrect.

Here's an example of how to create a service provider for this class...

php artisan make:provider ActiveCampaignProvider
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ActiveCampaignProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // --
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('ActiveCampaign',  function($app) {
            $config = $app['config']['services']['activecampaign'];
            return new \ActiveCampaign($config['url'], $config['key']);
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [\ActiveCampaign::class];
    }
}

Add this to config/services.php

    'activecampaign' => [
        'url' => env('ACTIVECAMPAIGN_URL'),
        'key' => env('ACTIVECAMPAIGN_API_KEY')
    ],

Then add those values to your .env file.

Now you can reference the singleton elsewhere in your code with something like this...

$ac = app('ActiveCampaign');

Simple example for adding a new contact

public function addContact(array $newContactData, \ActiveCampaign $ac)
{
    return $ac->api('contact/add', $newContactData)->success;
}

$ac will automatically be injected by Laravel's IOC container; it will be the singleton that you created in ActiveCampaignProvider.

This is all Laravel 101. You might consider perusing the docs a bit and familiarizing yourself with Laravel a bit more.

ryancwalsh commented 7 years ago

Thanks @QWp6t . One other step I needed to take to get this to work was to add this line to the 'providers' array in config/app.php: App\Providers\ActiveCampaignProvider::class,

fpena commented 7 years ago

Thanks @ryancwalsh and @QWp6t. This works well!