Laravel 5 Repositories

repository·master·Indexed 26 days ago

https://github.com/andersao/l5-repository

A package for Laravel applications designed to abstract the data layer using the Repository pattern. It provides core data access methods via RepositoryInterface, query filtering through RepositoryCriteriaInterface, caching via CacheableInterface, and data transformation with PresenterInterface. Includes Artisan commands like make:entity and make:repository for automated class generation, as well as RequestCriteria for dynamic URL-based searching and filtering.

Tokens
7.6K
Snippets
25
Records
48
Agent score
88%

What's inside l5-repository

  1. Laravel 13 Compatibility Requirements

    master

    For projects upgrading to or using Laravel 13 with this repository, note the following requirements:

    • Minimum PHP Version: 8.2
    • Supported Laravel Matrix: 8 / 9 / 10 / 11 / 12 / 13 (Laravel 5–7 are no longer supported).
    • Cache Configuration: If using cacheable repositories, you must whitelist criterion classes in config/cache.php under serializable_classes due to hardened deserialization in Laravel 13.
  2. Set up Orchestra Testbench for testing

    master

    To test the package within a real Laravel container, add orchestra/testbench to your require-dev dependencies. Create a tests/TestCase.php that extends Orchestra\Testbench\TestCase and registers the RepositoryServiceProvider via the getPackageProviders method.

    <?php
    
    namespace Prettus
    epository	ests;
    
    use Orchestra\Testbench\TestCase as OrchestraTestCase;
    use Prettus\Repository\Providers\RepositoryServiceProvider;
    
    abstract class TestCase extends OrchestraTestCase
    {
        protected function getPackageProviders($app): array
        {
            return [RepositoryServiceProvider::class];
        }
    }
  3. Upgrade to Laravel 13 Compatibility

    master

    To support Laravel 13 (illuminate/* ^13.0), you must widen the composer.json constraints and update the PHP requirement to ^8.2. This upgrade also involves modernizing the PHPUnit configuration to the PHPUnit 12 schema and ensuring compatibility with prettus/laravel-validation.

    "require": {
        "php": "^8.2",
        "illuminate/http": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/config": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/support": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/database": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/pagination": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/console": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/filesystem": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "illuminate/validation": "^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
        "prettus/laravel-validation": "~1.4|~1.5|~1.6|~1.7|~1.8"
    }
  4. Migrate to v3.0 (Laravel 13 support)

    master

    When upgrading to version 3.0, ensure your environment meets the new requirements and perform the following configuration updates:

    Requirements

    • PHP: 8.2 or higher.
    • Laravel: 8 or higher.

    Action Items

    1. Update Dependencies: Remove prettus/laravel-validation from your composer.json if it was only used transitively through this package. The source is now bundled directly under the Prettus\✨Validator namespace.
    2. Configure Cache Serialization: Laravel 13 hardens cache.serializable_classes to false by default. If you use the CacheableRepository trait, you must whitelist your concrete model and criterion classes in config/cache.php to prevent unserialization failures.
    3. Refresh Autoloading: Run composer dump-autoload to ensure the bundled validator source is correctly mapped.
    4. Verify Cache Time: CacheableRepository::getCacheTime() now always returns seconds. If your application logic was targeting Laravel 5.7 or earlier (which used minutes), you must multiply your $cacheMinutes value by 60.
    // Update config/cache.php to whitelist classes used in CacheableRepository
    'serializable_classes' => [
        Illuminate\Support\Collection::class,
        Illuminate\Pagination\LengthAwarePaginator::class,
        App\Repositories\Criteria\YourCriterion::class,
        App\Models\YourEloquentModel::class,
    ],
  5. Use Presenters and Transformers

    master

    Presenters wrap and render objects (usually via Fractal).

    Implementation Methods:

    1. Transformer Class: Create a class extending TransformerAbstract. Create a Presenter that returns this transformer in getTransformer(). Enable it in the repository via presenter().
    2. Transformable Model: Make your model implement Prettus\Repository\Contracts\Transformable and use the default Prettus\Repository\Presenter\ModelFractalPresenter in your repository.

    Usage:

    • Enable in repository: public function presenter() { return "App\\Presenter\\PostPresenter"; }
    • Enable in controller: $this->repository->setPresenter("App\\Presenter\\PostPresenter");
    • Skip presenter: $this->repository->skipPresenter()->all();
    use League\Fractal\TransformerAbstract;
    
    class PostTransformer extends TransformerAbstract
    {
        public function transform(\Post $post)
        {
            return [
                'id'      => (int) $post->id,
                'title'   => $post->title,
                'content' => $post->content
            ];
        }
    }
  6. Use RequestCriteria for Dynamic Filtering

    master

    The RequestCriteria enables dynamic searching and filtering via URL parameters.

    Setup:

    1. Define $fieldSearchable in your repository to specify which fields can be searched (supports relations like product.name).
    2. You can specify the operator (default is =) in the $fieldSearchable array (e.g., 'name' => 'like').
    3. Push the criteria in the repository boot() method or directly in the controller.

    URL Parameters:

    • search: Search for values (e.g., ?search=name:John Doe).
    • searchFields: Specify fields and operators (e.g., ?searchFields=name:like).
    • searchJoin: Change the join operator between multiple search terms (default is OR, use ?searchJoin=and for AND).
    • filter: Filter specific fields (e.g., ?filter=id;name).
    • orderBy / sortedBy: Sort results (e.g., ?orderBy=id&sortedBy=desc).
    • with: Include relationships (e.g., ?with=groups).
    class PostRepository extends BaseRepository {
        protected $fieldSearchable = [
            'name' => 'like',
            'email' // Default is "="
        ];
    
        public function boot(){
            $this->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        }
    }
  7. Migrate repository registration from version 1.0 to 2.0

    master

    When migrating from version 1.0 to 2.0, the method for associating a model with a repository changes.

    In version 1.0, you associated a model by passing it into the Repository constructor via parent::__construct($model).

    In version 2.0, you must extend BaseRepository and implement a model() method that returns the fully qualified class name (string) of the model.

    // Version 2.0 implementation
    use Prettus
    epository\Eloquent\BaseRepository;
    
    class PostRepository extends BaseRepository {
        
        /**
         * Specify Model class name
         *
         * @return string
         */
        function model()
        {
            return "App\\Post";
        }
    }
  8. Modernize phpunit.xml for PHPUnit 12

    master

    To support PHPUnit 12, replace the existing phpunit.xml with the new schema. This removes deprecated attributes like backupStaticAttributes and convertErrorsToExceptions, and adds a <source> block for coverage. Additionally, add .phpunit.cache and .phpunit.result.cache to your .gitignore file.

    <?xml version="1.0" encoding="UTF-8"?>
    <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
             bootstrap="vendor/autoload.php"
             colors="true"
             failOnWarning="true"
             failOnRisky="true"
             cacheDirectory=".phpunit.cache">
        <testsuites>
            <testsuite name="Prettus Repository Test Suite">
                <directory suffix="Test.php">./tests/</directory>
            </testsuite>
        </testsuites>
        <source>
            <include>
                <directory suffix=".php">./src/</directory>
            </include>
        </source>
    </phpunit>
  9. Implement Repository Caching

    master

    To add caching to your repository, implement CacheableInterface and use the CacheableRepository trait.

    Configuration: Settings can be managed in config/repository.php or overridden directly in the repository class.

    Repository Overrides:

    • $cacheMinutes: Set the lifetime of the cache.
    • $cacheOnly: Array of methods to cache.
    • $cacheExcept: Array of methods to exclude from caching.

    Cacheable Methods: all, paginate, find, findByField, findWhere, getByCriteria.

    use Prettus\Repository\Eloquent\BaseRepository;
    use Prettus\Repository\Contracts\CacheableInterface;
    use Prettus\Repository\Traits\CacheableRepository;
    
    class PostRepository extends BaseRepository implements CacheableInterface {
        use CacheableRepository;
    
        protected $cacheMinutes = 90;
        protected $cacheOnly = ['all', ...];
    
        function model() {
           return "App\\Post";
        }
    }