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

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.

Related

How to check that a dev dependency is not needed in production?

Since our project needs a library to run tests, this package is listed in the require-dev section of composer.json.
{
//...
"require": {
"php": "^7.4|^8.0",
},
"require-dev": {
"cache/array-adapter": "^1.1"
},
//...
}
During a manual code review, I realised that this library is being used in our production code too.
The fix is easy, we moved the corresponding package from the require-dev section to the require section.
{
//...
"require": {
"php": "^7.4|^8.0",
"cache/array-adapter": "^1.1"
},
"require-dev": {
},
//...
}
I'm searching an automatic way/test to avoid this kind of problem. I guess that our manual test during staging can avoid these kind of problem, but it isn't enough.
How to check that a dev-dependency isn't needed in our core-code?
You could implement this using PHPStan (or Psalm, or any other static analyzer): if you removed the dev dependencies and then run such a tool, it would notify you about missing classes from such a dependency.
But be warned: even if this helps to write more strict code, it might need some work in the beginning to implement proper return types all over your application
Another idea: also remove dev dependencies and run a usual test suite like PHPUnit or Behat.
I guess you could do it with deptrac. Although it's generally used to track internal architectural dependencies, nothing stops you from configuring it to track external dependencies.
It would require you manually configuring the "dev" layer with different "collectors", one for each dev dependency namespace, and a base layer for your App namespace.
Anything in App that depends on the dev layer would be a violation, unless explicitly allowed. You could even put this in CI (which is a common use-case of deptrac), where any violation would stop the deployment.
The configuration would be something like this (untested):
paths:
- ./src/
exclude_files: ~
layers:
- name: App
collectors:
- type: className
regex: App\\.*
- name: Dependencies
collectors:
- type: className
regex: Symfony\\Bundle\\MakerBundle\\.*
- type: className
regex: Cache\\Adapter\\PHPArray\\.*

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';

Using illuminate/pagination outside laravel

I'm building custom project and for now for database connection i used illuminate/database the eloquent model.
But i need samo pagination to continue my development i installed via composer illuminate/pagination and i cant configure it propertly i searched all over the internet no documentation for using with illuminate pagination or how to configure it.
I have function
User::all();
Where i fetch all my users successfully but i need to make paginate when i try to use ->paginate() method not found.
The composer is set coorectly and all my files are loaded.
Any tips how to set up the illuminate/pagination library ?
Btw i developed custom framework where i have controller and models. All my models are Eloquent models.
Thanks
You can check out the forPage() method on the Collection itself.
https://laravel.com/docs/5.8/collections#method-forpage
This worked for me:
$collection->forPage($_GET["pagenr"], $perpage);
use :
composer require illuminate/pagination
for example : if need Controllers and Models add autoload psr-4
composer.json
{
"name": "illuminate-example/eloquent",
"description": "Implementation of Database Queries with illuminate and Eloquent",
"type": "project",
"require": {
"illuminate/database": "^6.17",
"illuminate/pagination": "^6.17"},
"autoload":
{"psr-4":
{ "Controllers\\": "app/controllers/",
"Models\\": "app/models/"
}
}
}
Not sure if this is helpful anymore, but I was having the same issue and came across this: https://laracasts.com/index.php/discuss/channels/general-discussion/class-paginator-does-not-exist-laravel-42
Seems as though it's not possible outside laravel.

Adding a custom Artisan command with Behat

I've registered a custom Artisan command:
Artisan::add(new MigrateAll);
The class resides in app/commands (default location)
However when I run Behat I get the error:
Class 'MigrateAll' not found
Artisan is called in Behat for setting up the DB:
/**
* #static
* #beforeSuite
*/
public static function setUpDb()
{
Artisan::call('migrate:install');
//...
}
Do I need to give it a namespace? (I could not find the correct way to call the Artisan::add command with a namespaced class)
This is somewhat related to your earlier question. Your Behat test suite runs in a separate process independently of your app and knows nothing about the configuration. This also applies to the autoloading in your bootstrap and the autoloading would be the most likely reason why classes don't get found. This should be easily fixed by using Composer to autoload your own sources and vendor packages (both in your app and in your test suite).
# composer.json
{
"require": {
"…": "…"
},
"autoload": {
"psr-0": {
"": "../src"
}
}
}
// Include composer's autoloader in your `setUp()` / bootstrap / index.php.
include __DIR__ . '../vendor/autoload.php';
Take that process separation as a rule and keep in mind that Laravel like any other framework requires a whole bunch of other configuration. Since you are trying to use the database component, your next issue will be with that, because it won't be configured in your test suite.
The best approach is to create separate bootstrap file for Behat, which would inherit most lines from your normal bootstrap, where you need to pass the necessary configuration and do this:
/**
* #static
* #beforeSuite
*/
public static function setUp()
{
include_once('bootstrap.php');
}
If you configured your behat environment with this tut (Laravel, BDD And You: Let’s Get Started), after you added a new command, you need to $ composer dump-autoload to make behat to know the command.

Using a non-laravel package on Laravel 4

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

Categories