How to require and configure a dependency in laravel? - php

I wish to add chargebee php api to my laravel project
For that I first ran
composer require chargebee/chargebee-php
This added the chargebee API to vendor/chargbee
Next thing I would need to do is to include and configure the api. This can be done by:
require_once base_path('vendor/chargebee/ChargeBee.php');
ChargeBee_Environment::configure("your_site", "{your_site_api_key}");
My question is where should i do this? I would like the including of ChargBee.php and configuring it to be in a generic place so i can later use it in any Controller and it would already be set up. What is the default way to do this in Laravel?

You should set up a new service provider, like described in the official documentation.
Hint 1: Run php artisan make:provider ChargeBeeServiceProvider from command line to generate the new service provider.
Hint 2: take a closer look at the register() method. You should register the ChargeBee "service" there, most probably like a singleton. That's the place, where the API configuration should be put.
Since autoload is being used in the chargebee library (see its composer.json), there is no need for the require_once base_path('vendor/chargebee/ChargeBee.php'); line. Just simply use the classes.

Related

Where to put things in Laravel 5.1

I'm a bit confused about where something like this belongs to Laravel.
I want to write a web service client wrapper in laravel, and I want to access it like this:
\MyWSClient::getSomeInfoAbout($someId);
then the code will connect to the web service to http://www.someapi.com/api/getSomeInfoAbout?id=$someid&type=json with OAuth2 or some token requests, then fetch the data, keep token information until it expires, refresh token if needed etc.
But where will I put the code? In the vendor directory as a new package? I'm moving this code from a computer to another computer except vendor,storage and node_modules folders, because they are huge and when I do this, I will have to move only one folder in the vendor directory. And I'll need to publish a package under development to composer if I want portability etc.
Is there any other way to do something like this?
I think I've found the answer.
First I needed to use jeroen-g/laravel-packager package to create a new package using artisan console. I could've done that by hand, but I didn't know the required files.
Second, I've created a new package in the packages folder with my desired class name.
Third, I've added the provider and the alias for the class in app.php.
After that, I've created a test method in my controller and wrote a route for that. I called the static method I've written in the SkeletonClass the packager created for me.
And it worked with some tweaking after creation.
I've used php artisan packager:new tpaksu mypackage --i command for an interactive package creation which is cool.
Note: I've just learned the existence of this package, I'm not advertising it :)

Symfony console application: dependency injection [duplicate]

This question already has an answer here:
How to use DependencyInjection from symfony in stand alone application with commands?
(1 answer)
Closed last year.
A Symfony novice here. After reading some of the Symfony documentation and some answers here at SO, I am now almost completely confused.
I am trying to use the console application component and create a small db-aware console application.
Many people state that in order to use Symfony's DI features it would be enough to inherit my command class not from Symfony\Component\Console\Command\Command but from ContainerAwareCommand.
However when I try this I get a Method Not Found error on an application::getKernel() call.
I have a feeling that DI features are in fact not available in a console application based on the console component. Is there another kind of Symfony console application, for example, based on the full-blown framework?
I very much like the simple framework provided by the console component Symfony\Component\Console\Application. But the question is then - what to do for dependency injection and DBAL? All examples that I find seem to refer to the full Symfony framework and get me just all the more stuck.
Just a quick update on my progress if anybody stumbles upon the same problems.
I incorporated into my project the PHP-DI dependency injection framework, which seems to be working fairly well with no configuration (so far) - it figures out quite a lot by reflection, actually.
The same way, Doctrine\DBAL is included as a standalone library (I opted against the O/RM part of it, as it is really a tiny project and I'm on a much firmer ground with SQL than anything else) and the connection is simply returned by a connection provider which is injected wherever needed by the DI.
One thing I couldn't figure out is how to have the command classes instantiated by the DI library without my help, so I actually had to inject the container itself into my overridden application class and override the getDefaultCommands() where I then pull the instances out of the container manually. Not ideal but will have to do for now.
If your command extends ContainerAwareCommand
...
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
...
class MyCommand extends ContainerAwareCommand
{
The DI container is available with the getContainer() method. (like in a standard controller), ex:
$this->validator = $this->getContainer()->get('validator');
I don't know if your question is still relevant, but I have an answer as I stumbled across the same problem here.
You just have to create the kernel yourself and give it to the \Symfony\Bundle\FrameworkBundle\Console\Application that extends the basic \Symfony\Component\Console\Application.
<?php
// CronRun.php
require __DIR__.'/../../../../vendor/autoload.php';
require_once __DIR__.'/../../../../app/AppKernel.php';
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$application->add(new \KingdomHall\TaskBundle\Command\CronCommand());
$input = new \Symfony\Component\Console\Input\StringInput('k:c:r');
$application->run($input);
You could use a solution I just pushed it to packagist.org. Includes full working symfony/dependency-injection. You're welcome to give it a shot. use composer to create your own project composer create-project coral-media/crune project_dir or just clone the repository.
https://packagist.org/packages/coral-media/crune
You only need to install DBAL dependencies (I don't suggest ORM if you don't really need it). Configure connection parameters in .env and just define a service to handle connection. That service can be injected in your Commands using public setMyService($myService) method with #required annotation. Also you could create a Connection class and bind is as parameter in your command constructor.The crune boilerplate also supports autowire and autoconfiguring features.

Where can you put a Service Provider Class in Laravel?

I want to create a server provider in Laravel.
I want this service provide to live under its own namespace.
Path\To\My\AwesomeServiceProvider
Where should I put this class? Normally I'd drop a custom class in
app/models
However, app/models isn't added as an autoload source until after app/start/global.php executes. This is too late for a service provider, as all service providers are registered in bootstrap/start.php.
Is there a way to create a service provider without placing the class in composer's vendor folder or monkeying with your composer.json classmap?
Put another way, is there a location where Laravel will autoload classes from prior to bootstrap/start.php being loaded that doesn't require additional composer configuration.
(For the inevitable "why don't you justs", the reason I want to avoid composer is I'm trying to figure out the bare minimum code and configuration needed for a service provider in Laravel)
you dont need to modify anything inside vendor.
You only need to define one of the possible autoload types for your new class or directory inside the composer.json of your project.
https://getcomposer.org/doc/04-schema.md#autoload
as alternate you can directly use a plain php implementation of the autoloading
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md

Dependency injection in a symfony console command? Not full Symfony application

I've seen this How can i inject dependencies to Symfony Console commands? but that answer doesn't really give enough information and is already explained here http://symfony.com/doc/current/cookbook/console/console_command.html
The problem is a containerAwareCommand doesn't work with the setup here http://symfony.com/doc/current/components/console/introduction.html
In order to use containerAwareCommand from what I can tell, I need my application to use
Symfony\Bundle\FrameworkBundle\Console\Application
instead of
Symfony\Component\Console\Application
But using the frameworkBundle Application class requires an instance of KernelInterface and won't allow me to pass in a name and version to my application.
Here is what I have that won't work with containerAwareCommands
#!/usr/bin/env php
<?php
require __DIR__.'/../src/vendor/autoload.php';
$app = new Symfony\Component\Console\Application('spud', '0.0.1');
$app->add(new Isimmons\Spudster\Console\Commands\SayHelloCommand);
$app->run();
The command it's self runs but I get an error when trying to use getContainer
Call to undefined method Symfony\Component\Console\Application::getKernel()
On a related topic which will probably come up next, The documentation for registering a class in the container shows using a app/config/config.php file. But I don't have an app directory since this is not a full symfony application. My base directory in which all of the app except for the file above is located, is src/lib. If I can figure out the first part above, will symfony be able to find the config file at src/lib/config/config.php?
You can use Consolefull application.
Consolefull is a simple library to work with Symfony Console Component and Symfony Dependency Injection Component

Advice needed for Laravel 4 project structure

I'm quite new to Laravel 4 (Laravel is my first PHP MVC framework) and need a little help structuring my project.
1/ I need to include the the json-rpc classes found here jsonrpcphp.org in my project and am not quite sure the best place to put these.
2/ Where is the best place to do my initial setup/connection to my data source? Should this be inside of my controller or should this be placed elsewhere?
require_once 'jsonRPCClient.php';
$connection = new jsonRPCClient('http://user:password#127.0.0.1');
I think and pretty sure the best way to do it is to create a Service
Put anywhere securely and can be easily accessed via composer. Look into how add autoloading to composer http://getcomposer.org/doc/01-basic-usage.md#autoloading
as I said, create a service. look into Laravel IoC Container http://laravel.com/docs/ioc and How to define Service Provider
see example: DatabaseServiceProvider
Related: optional for nice syntax create a Facade for it.

Categories