Giter Club home page Giter Club logo

wouterjeloquentbundle's Introduction

WouterJEloquentBundle

The WouterJEloquentBundle claims to integrate the Eloquent ORM into the Symfony framework.

Maintained Releases

Only the latest release of this bundle is maintained. Backwards compatible support for new versions of PHP, Symfony and Laravel are considered bug fixes. Dropping support for old versions is considered a feature.

New releases will be made as much as once a week following semantic versioning. The default branch (2.x) will be released as minor or patch version, depending on the changes with the last release (features or only bug fixes).

Installation

Step 1: Download the Bundle

Open a command console, enter your project directory and run the following command to download the latest stable version of this bundle:

$ composer require wouterj/eloquent-bundle

This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.

When you want to use useful make commands (e.g. make:model), also make sure you have the Symfony MakerBundle installed.

Step 2: Enable the Bundle

If you're using Symfony Flex, the previous step already got you up and running and you can skip this step!

Otherwise, enable the bundle by adding it to the list of registered bundles in the app/AppKernel.php file of your project:

<?php
// config/bundles.php

return [
    // ...
    WouterJ\EloquentBundle\WouterJEloquentBundle::class => ['all' => true],
];

Step 3: Configure the Database

To use the Eloquent ORM, configure a connection by setting the correct environment variables in .env.local:

# .env.local
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=symfony
DB_USERNAME=root
DB_PASSWORD=s3cr3t

If you're not using Symfony Flex, create the configuration file yourself:

# config/packages/eloquent.yaml
wouterj_eloquent:
    driver:   mysql
    host:     localhost
    database: db_name
    username: root
    password: pass
    prefix:   ~

For more information, refer to the documentation below.

Table of Content

  1. Installation
    1. Step 1: Download the Bundle
    2. Step 2: Enable the Bundle
    3. Step 3: Configure the Database
  2. Usage
    1. Query Builder
    2. Eloquent ORM
    3. Using Services instead of Facades
  3. Migrations and Seeding
    1. Running seeders
    2. Setting up
    3. Generating migrations
    4. Running migrations
    5. Rolling migrations
    6. Refreshing the database
  4. Using Models in Forms
    1. Binding the Object to the Form
    2. Form Type Guessing
    3. Form Validation
  5. Using the Eloquent User Provider
    1. Creating the User Model
    2. Configuring the User Provider
  6. Events and Observers
    1. Register Listeners
    2. Observers
      1. Observers as Services
  7. Configuration
    1. Full configuration
    2. Connections
      1. Drivers
      2. Default connection
    3. Eloquent
    4. Aliases
  8. License
  9. Contributing
  10. Backwards Compatibility

License

This project is licensed under the MIT license. For more information, see the license file included in this bundle.

Contributing

I love contributors. You can submit fixes, report bugs, share your opinion, advocate this bundle or just say "hello". I welcome anything that makes this project better.

wouterjeloquentbundle's People

Contributors

andriuspetrauskis avatar brzuchal avatar chalasr avatar demoneno4ec avatar duayres avatar edudobay avatar fabpot avatar fragkp avatar frankdejonge avatar g9rga avatar javiereguiluz avatar mariano-gomez avatar nouwaarom avatar richtermeister avatar rivomanana avatar robinvdvleuten avatar theofidry avatar wouterj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

wouterjeloquentbundle's Issues

Warning in service wiring because of missing "Twig_Environment"

I use Symfony Framerowk but no Twig, so I get this warning:

Warning: Class "Twig_Environment" not found in .../vendor/wouterj/eloquent-bundle/src/Twig/SqlFormatterExtension.php on line 18

The above-mentioned SqlFormatterExtension should be wired only if there is a presence of Twig being detected first.
No need for this in applications that don't have HTML rendering.\


Using the latest version 2.2.1

I would like to get some advice

Hi Wouter J , this is my first time using symfony , and I want him to support Oracle , so , can you give me some guidance ?

"A facade root has not been set."

I'm having this error message when i execute
./bin/console eloquent:seed

in my eloquent config file i have this:

wouterj_eloquent:
# ...
    eloquent: true
    aliases:
      db: true

And my DatabaseSeeder File looks like this:

namespace App\Seed;

use WouterJ\EloquentBundle\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder {
    public function run() {
        for ($i = 1; $i<=10; $i++) {
            DB::table('juego')->insert([
                'id' => $i,
                'secret' => 'secret' . $i,
                'name' => 'cliente' . $i,
            ]);
        }
    }
}

What am i missing here?

Is this project still maintained?

I would like to use this project, but last commit was in november. Eloquent version is outdated too. Is this project still maintained?

Form::handleRequest integration.

Hello,
I was trying to use internal symfony Form::handleRequest using your Eloquent bundle, but I got errors on mixins annotations inside Illuminate\Database\Eloquent\Model (not imported).

        $entity = new Book(); // [Object {id: '', name: ''}]
        $form = $this->createForm(new BookType(), $entity, array(
            'action' => $this->generateUrl('book_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));
        
        $form->handleRequest($request);//here I get the error

Error: [Semantical Error] The annotation "@mixin" in class Illuminate\Database\Eloquent\Model was never imported. Did you maybe forget to add a "use" statement for this annotation?

Another thing is the validation, any ideas on validation using eloquent and symfony since validation on doctrine is inside the models and annotation based?

Thanks

Seeder class names losses their first letter

Hi guys, i've found that executing:
./bin/console eloquent:make:seeder --target=migrations/seeds/SomeClass.php SomeClass, a file is created in migrations/seeds/ with the correct filename. But inside the file, a class is defined with the name "omeClass"

The problem is in class wouterj\eloquent-bundle\src\Command\SeederMakeCommand.php, on line 65 ($class = substr($name, $lastPos + 1);)

that +1 shouldn't exists

Update illuminate packages

You should update the illuminate packages to ^5.5 instead of ~5.5. Illuminate won't introduce BC breaks in minors. So that's pretty safe to do.

eloquent:seed error

Looking at the eloquent:seed command help, it says that to specify a Seeder class, we must write the command this way:

php ./bin/console eloquent:seed Acme\DemoBundle\Seed\UserTableSeeder

Thing is, that doesn't works. But after taking a look at the code, i've realized that using it this way, it works:

php ./bin/console eloquent:seed Acme\\DemoBundle\\Seed\\UserTableSeeder

That double backlash should be treated, i think

Eloquent not booted

I got an error while using the User model inside a LoginFormAuthenticator class (I'm implementing guard component). It says Error: Call to a member function connection() on null!

After looking around for a while I figured out Eloquent has not booted! And after adding a $capsuleDefinition->addMethodCall('bootEloquent'); inside the WouterJ\EloquentBundle\DependencyInjection\WouterJEloquentExtension@loadCapsule it worked fine.

Error with pagination

Whenever I Use the pagination I get the following error:

Attempted to load class "Paginator" from namespace "Illuminate\Pagination". Did you forget a "use" statement for "Illuminate\Contracts\Pagination\Paginator"?

Can you enable more Aliases to use the paginator class?

Postgresql Schemas

There is no param on eloquent.yaml to set schema for postgresql database.

I was able to make it work by editing the file: WouterJEloquentBundle/src/DependencyInjection/Configuration.php and inserting the param 'schema' to the arrays on lines 82, 86 and adding: ->scalarNode('schema')->defaultValue('')->end() below line 139.

Can you add this to the master please ?

Other drivers

Hello.

How can I add new driver, for example Vertica driver?
Is it possible?

variation of postgres driver names

illuminate searches for pgsql
whilst wouterj searches for postgres
and doctrine registers postgres driver as pdo_pgsql

can you add the validation of config for drivers ->ifNotInArray(['mysql', 'pgsql', 'sql server', 'sqlite'])
to more possible combinations ?
-postgres
-pgsql
-pdo_pgsql
-postgresql

??

if i use all these names above it wont work unless i change the validation from postgres to pgsql and use pgsql

Allow service observers to bind to model in tag

E.g.

app.user_observer:
    class: AppBundle\Observer\UserObserver
    tags:
        - { name: wouterj_eloquent.observer, model: AppBundle\Model\User }

This requires some more work, as it needs to bind on each request instead of just once during container building. This might require adding a new initializers.

Installation problem

I have symfony 4.0 version installed.

Your requirements could not be resolved to an installable set of packages.

Problem 1
- Conclusion: don't install symfony/dependency-injection v3.4.0
- Installation request for symfony/dependency-injection (locked at v4.0.0) -> satisfiable by symfony/dependency-injection[v4.0.0].
- Conclusion: remove symfony/console v4.0.0
- Conclusion: don't install symfony/console v4.0.0
any suggest?

Thank you

UndefinedMethodException while trying to access method cloneVars

Hi,
I've set up the latest version of this bundle (0.5) and set up everything following the documentation. The first problem I've seen is that
use WouterJ\EloquentBundle\Facade\DB;
should be
use Illuminate\Support\Facades\DB;

But even with this I receive an UndefinedMethodException while trying to retrieve a result set using DB:table...->get();

UndefinedMethodException in EloquentDataCollector.php line 35:
Attempted to call an undefined method named "cloneVar" of class "WouterJ\EloquentBundle\DataCollector\EloquentDataCollector".

PS: I've also added the aliases:true into the config and removed the 'use', but got the same error.
PS2: Symfony version 2.8
PS3: Symfony\Component\HttpKernel\DataCollector\DataCollector have the method, and your DataCollector extends from it... idk what to do tho

"A facade root has not been set." exception

I have this configuration in the eloquent.yaml:

wouterj_eloquent:
driver: '%env(DB_CONNECTION)%'
host: '%env(DB_HOST)%'
port: '%env(DB_PORT)%'
database: '%env(DB_DATABASE)%'
username: '%env(DB_USERNAME)%'
password: '%env(DB_PASSWORD)%'
eloquent: true
aliases:
db: true

And when i try to use this query
$juegos = DB::table('juegos')->paginate(self::JUEGOS_POR_PAGINA, ['*'], 'page', $page);

i get an exception with the message "A facade root has not been set". The same happens if i comment the eloquent and/or the aliases (with its db subkey) parameters. #

Attempted to call an undefined method named "getCasts"

This error is being thrown in a bundle with no association to anything regarding to the WouterJEloquentBundle

Fatal error: Uncaught Symfony\Component\Debug\Exception\UndefinedMethodException: Attempted to call an undefined method named "getCasts" of class "Content\PollBundle\Entity\PollVersion". in /var/www/html/vendor/wouterj/eloquent-bundle/src/Form/EloquentModelTypeGuesser.php on line 23

Symfony\Component\Debug\Exception\UndefinedMethodException: Attempted to call an undefined method named "getCasts" of class "Content\PollBundle\Entity\PollVersion". in /var/www/html/vendor/wouterj/eloquent-bundle/src/Form/EloquentModelTypeGuesser.php on line 23

This is occurring in a couple of our bundles

Add form types for relational model

This continues #67

The bundle should provide some eloquent model form type for relations between models. Just like DoctrineBundle provides. A comment by @duayres from #67 :

@wouterj Well, I've made some progress here but I can't find a way to remap relation to relation**_id**
Here is my Gist (UGLY code, sorry 🤢).

Since i'm using builder->add('author' (and not author**_id**), the time it will persist, author collumn can't be found on the database... so another quick-fix:

    // inside Author.php (of a book) Model
    public function fixRelations(){
        foreach ($this->attributes as $attribute => $value) {
            if (substr($attribute, -3)=="_id"){
                //maps ex. 'author' to correct field 'author_id'
                $this->attributes[$attribute]=$this->attributes[substr($attribute, 0, -3)];
                unset($this->attributes[substr($attribute, 0, -3)]);
            }
        }
    }

Any help will be very appreciated

Call to a member function connection() on null

I keep getting this error when trying to run the migrations! This is the stack trace

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Error: Call to a member function connection() on null


Exception trace:
 () at /vagrant/movies/vendor/illuminate/support/Facades/Schema.php:28
 Illuminate\Support\Facades\Schema::getFacadeAccessor() at /vagrant/movies/vendor/illuminate/support/Facades/Facade.php:144
 Illuminate\Support\Facades\Facade::getFacadeRoot() at /vagrant/movies/vendor/illuminate/support/Facades/Facade.php:231
 Illuminate\Support\Facades\Facade::__callStatic() at /vagrant/movies/app/migrations/2016_10_23_113543_create_users_table.php:19
 Illuminate\Support\Facades\Schema::create() at /vagrant/movies/app/migrations/2016_10_23_113543_create_users_table.php:19
 CreateUsersTable->up() at /vagrant/movies/vendor/illuminate/database/Migrations/Migrator.php:162
 Illuminate\Database\Migrations\Migrator->runUp() at /vagrant/movies/vendor/illuminate/database/Migrations/Migrator.php:130
 Illuminate\Database\Migrations\Migrator->runMigrationList() at /vagrant/movies/vendor/illuminate/database/Migrations/Migrator.php:97
 Illuminate\Database\Migrations\Migrator->run() at /vagrant/movies/vendor/wouterj/eloquent-bundle/src/Command/MigrateCommand.php:46
 WouterJ\EloquentBundle\Command\MigrateCommand->execute() at /vagrant/movies/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:256
 Symfony\Component\Console\Command\Command->run() at /vagrant/movies/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:837
 Symfony\Component\Console\Application->doRunCommand() at /vagrant/movies/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:187
 Symfony\Component\Console\Application->doRun() at /vagrant/movies/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:80
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /vagrant/movies/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:118
 Symfony\Component\Console\Application->run() at /vagrant/movies/bin/console:27
 {main}() at /vagrant/movies/bin/console:0
``

Documentation

Is there any reason why the doc is in .rst? It doesn't render well on GitHub :/

eloquent:migrate:fresh command fail without --database parameter

Hello,

Version: 2.2.1

Using the command bin/console eloquent:migrate:fresh without any paramter leads to an error whereas the help output says we can use it without any parameter: eloquent:migrate:fresh [--database DATABASE] [--force] [--path PATH] [--seed] [--seeder SEEDER]

$ bin/console eloquent:migrate:fresh                                                                                                                                                           
[critical] Error thrown while running command "eloquent:migrate:fresh". Message: "WouterJ\EloquentBundle\Command\MigrateFreshCommand::dropAllTables(): Argument #1 ($database) must be of type string, null given, called in /Volumes/Projects/customers-service/vendor/wouterj/eloquent-bundle/src/Command/MigrateFreshCommand.php on line 58"


In MigrateFreshCommand.php line 79:
                                                                                                                                                                                                                                          
  WouterJ\EloquentBundle\Command\MigrateFreshCommand::dropAllTables(): Argument #1 ($database) must be of type string, null given, called in /Volumes/Projects/customers-service/vendor/wouterj/eloquent-bundle/src/Command/MigrateFresh  
  Command.php on line 58                                                                                                                                                                                                                  
                                                                                                                                                                                                                                          

eloquent:migrate:fresh [--database DATABASE] [--force] [--path PATH] [--seed] [--seeder SEEDER]

If you provide the --database default parameter it throw another error saying that --path is required.
The workaround is to force the --database DATABASE AND --path PATH paramters but I think both should be optional.

Thanks

eloquent:migrate throws Call to a member function getRequire() on null

When I run the $ php bin/console eloquent:migrate command it fails with a Call to a member function getRequire() on null error.

Steps to recreate:

  1. $ symfony new symfony-eloquent && cd symfony-eloquent
  2. $ composer require wouterj/eloquent-bundle
  3. $ composer require --dev symfony/maker-bundle
  4. $ php bin/console make:model Post
  5. $ php bin/console eloquent:migrate:install
  6. $ php bin/console make:eloquent-migration --create=posts create_posts_table
  7. $ php bin/console eloquent:migrate

Packages:

  1. "symfony/framework-bundle": "6.3.*"
  2. "wouterj/eloquent-bundle": "^2.4"
  3. "symfony/maker-bundle": "^1.49"

PHP:

  1. PHP 8.1.6

Model:

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
}

Migration:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use WouterJ\EloquentBundle\Facade\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('post', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('post');
    }
};

`Migrator@requireFiles` definition not compatible with parent

The method WouterJ\EloquentBundle\Migrations\Migrator@requireFiles signature is not compatible with the parent method definition, and this throws a runtime exception. It could be changed to this:

class Migrator extends LaravelMigrator
{
    //...
    public function getMigrationFiles($path)
    {
        $files = Finder::create()->name('*_*.php')->in($path)->sortByName();

        if (0 === count($files)) {
            return [];
        }

        $migrations = [];
        /** @var SplFileInfo $file */
        foreach ($files as $file) {
            $migrations[] = $file->getRealPath();
        }

        return $migrations;
    }

    public function requireFiles(array $files)
    {
        foreach ($files as $file) {
            require_once $file;
        }
    }
}

QueryBuilder Result in Array format PDO::FETCH_ASSOC

First, thank you so much for making this package, it is amazing!

It would be great to get query builder results as an associative array.

I see in vendor/illuminate/database/Connection.php:
line 102:
protected $fetchMode = PDO::FETCH_OBJ;

in file vendor/illuminate/database/Capsule/Manager.php:
line 47:
protected function setupDefaultConfiguration()
{
$this->container['config']['database.fetch'] = PDO::FETCH_OBJ;
$this->container['config']['database.default'] = 'default';
}

Is there currently an easy way to update the Illuminate container config? What do you recommend is the best way to set the database.fetch = PDO::FETCH_ASSOC?

thanks!

Data collector crash debug toolbar with subrequest

If you use render twig finction, debug panel wil not be loaded properly due unserialize error.
I think problem is after eloquent is loaded there is PDO object in connection and as say in symfony docs:

As the profiler serializes data collector instances, you should not store objects that cannot be serialized (like PDO objects) or you need to provide your own serialize() method.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.