Easy Repository pattern for PHP Phalcon framework.

Overview

Phalcon Repositories

License Latest Stable Version Latest Unstable Version Build Status

Introduction

Phalcon Repositories lets you easily build repositories for your Phalcon models, for both SQL and Mongo drivers.

PHP 7.1+ and Phalcon 3.2+ are required.

Installation

Phalcon Repositories can be installed through Composer, just run composer require michele-angioni/phalcon-repositories.

Usage with SQL Drivers

The abstract class AbstractRepository consists of a model wrapper with numerous useful queries to be performed over the Phalcon models. This way implementing the repository pattern becomes straightforward.

As an example let's say we have a MyApp\Models\Posts model.

The easiest way to create a Posts repository is to define a class as such

<?php

namespace MyApp\Repos;

use MicheleAngioni\PhalconRepositories\AbstractRepository;
use MyApp\Models\Posts;

class PostsRepository extends AbstractRepository
{
    protected $model;

    public function __construct(Posts $model)
    {
        $this->model = $model;
    }
}

Suppose now we need the Post repository in our PostController. For example we can retrieve a Post this way

<?php

namespace MyApp\Controllers;

use MyApp\Repos\PostsRepository as PostsRepo;
use Phalcon\Mvc\Controller;
use MyApp\Models\Posts;

class PostsController extends Controller 
{
    
    public function showAction($idPost)
    {
        $postsRepo = new PostsRepo(new Posts());
        
        $post = $postsRepo->find($idPost);

        // Use the retrieved post
    }
}

We could also bind out repository to the container through the Phalcon dependency injection. We just need to add a new postRepo service in our bootstrap file

$di->set('postsRepo', function () {
    return new MyApp\Repos\PostsRepository(new \MyApp\Models\Posts());
});

and than use it in the controller

<?php

namespace MyApp\Controllers;

use Phalcon\Mvc\Controller;

class PostsController extends Controller 
{
    
    public function showAction($idPost)
    {
        $postsRepo = $this->getDI()->getPostsRepo();
        
        $post = $postsRepo->find($idPost);

        // Use the retrieved Post
    }
}

Usage with MongoDB

The abstract class AbstractCollectionRepository, similary to AbstractRepository, consists of a model wrapper with numerous useful queries to be performed over the Phalcon collections. This way implementing the repository pattern becomes straightforward.

As an example let's say we have a MyApp\Models\Posts collection

<?php

namespace MyApp\Models;

use Phalcon\Mvc\MongoCollection;

class Posts extends MongoCollection
{
    use \MicheleAngioni\PhalconRepositories\MongoFix; // Fix for Phalcon 3.1.x with PHP 7.1

    [...]
}

The easiest way to create a Posts repository is to define a class as such

<?php namespace MyApp\Repos;

use MicheleAngioni\PhalconRepositories\AbstractCollectionRepository;
use MyApp\Models\Posts;

class PostsRepository extends AbstractCollectionRepository
{
    protected $model;

    public function __construct(Posts $model)
    {
        $this->model = $model;
    }
}

Suppose now we need the Post repository in our PostController. For example we can retrieve a Post this way

<?php

namespace MyApp\Controllers;

use MyApp\Repos\PostsRepository as PostsRepo;
use Phalcon\Mvc\Controller;
use MyApp\Models\Posts;

class PostsController extends Controller
{

    public function showAction($idPost)
    {
        $postsRepo = new PostsRepo(new Posts());

        $post = $postsRepo->find($idPost);

        // Use the retrieved Post
    }
}

We could also bind out repository to the container through the Phalcon dependency injection. We just need to add a new postRepo service in our bootstrap file

$di->set('postsRepo', function () {
    return new MyApp\Repos\PostsRepository(new \MyApp\Models\Posts());
});

and than use it in the controller

<?php

namespace MyApp\Controllers;

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{

    public function showAction($idPost)
    {
        $postsRepo = $this->getDI()->getPostsRepo();

        $post = $postsRepo->find($idPost);

        // Use the retrieved post
    }
}

Method list

The AbstractRepository and AbstractCollectionRepository empower automatically our repositories of the following public methods:

  • all()
  • find($id)
  • findOrFail($id)
  • first()
  • firstOrFail()
  • firstBy(array $where = [])
  • firstOrFailBy(array $where = [])
  • getBy(array $where = [])
  • getByLimit(int $limit, array $where = [])
  • getByOrder(string $orderBy, array $where = [], string $order = 'desc', int $limit = 0)
  • getIn(string $whereInKey, array $whereIn = [], string $orderBy = null, string $order = 'desc', int $limit = 0)
  • getNotIn(string $whereNotInKey, array $whereNotIn = [], string $orderBy = null, string $order = 'desc', int $limit = 0)
  • getInAndWhereByPage(int $page = 1, int $limit = 10, string $whereInKey = null, array $whereIn = [], $where = [], $orderBy = null, string $order = 'desc')
  • getByPage(int $page = 1, int $limit = 10, array $where = [], string $orderBy = null, string $order = 'desc')
  • create(array $inputs = [])
  • updateById($id, array $inputs)
  • destroy($id)
  • destroyFirstBy(array $where)
  • count()
  • countBy(array $where = [])

The AbstractRepository contains also the methods:

  • getByGroupBy(string $groupBy, array $where = [], bool $addCounts = false)
  • truncate()

while the AbstractCollectionRepository allows for aggregations through:

  • getAggregate(array $match = [], array $project = [], array $group = [], int $limit = 0)

The $where parameter with SQL drivers

The $where parameter allows the use of various operators with the SQL driver, other than the equals =, even the LIKE keyword.

The following formats are supported:

  • 'key' => 'value'

    Examples:

    $where = ['username' => 'Richard']
  • 'key' => ['value', 'operator']

    Examples:

    $where = ['age' => [30, '=']]
    $where = ['age' => [30, '<']]
    $where = ['age' => [30, '>']]
    $where = ['username' => ['%Fey%', 'LIKE']]
  • ['key1%OR%key2'] => ['value', 'operator']

    Examples:

    `$where = ['username%OR%description' => ['%Feynman%', 'LIKE']]`

SQL Injection

The AbstractRepository and AbstractCollectionRepository use bind parameters for all $id and $where clauses. $inputs parameters in create and update queries are automatically escaped by Phalcon.

The security of the other parameters ($whereInKey, $whereIn, $orderBy, $order, $limit etc.) is up to you.

Testing

Install dependencies with composer install and then run vendor/bin/phpunit tests.

Contribution guidelines

Phalcon Repositories follows PSR-1, PSR-2 and PSR-4 PHP coding standards, and semantic versioning.

Pull requests are welcome.

License

Phalcon Repositories is free software distributed under the terms of the MIT license.

You might also like...
YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic.

YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic. It is built based on the combination of ideas from the Yii framework and Laravel framework (yl).

PHP implementation of circuit breaker pattern.

What is php-circuit-breaker A component helping you gracefully handle outages and timeouts of external services (usually remote, 3rd party services).

PHP regexp pattern matching Unicode emojis

Emoji pattern This package provides regexp patterns to match Unicode emojis. All forms of emojis are matched, including: Single-character emoji ( šŸ‘ )

Design Pattern Examples in PHP

Design Patterns in PHP This repository is part of the Refactoring.Guru project. It contains PHP examples for all classic GoF design patterns. Each pat

ImplementaĆ§Ć£o do Composite Pattern Utilizando PHP
ImplementaĆ§Ć£o do Composite Pattern Utilizando PHP

Composite Pattern - PHP ImplementaĆ§Ć£o do Composite Pattern Utilizando PHP DescriĆ§Ć£o O Composite Pattern Ć© um padrĆ£o de projeto estrutural que permite

Phalcon PHP Meta tags Service

About Phalcon meta tags plugin for PhalconPHP. This plugin allows you to easily and flexibly customize the meta tags of your view. If this plugin help

PHP Profiler & Developer Toolbar (built for Phalcon)
PHP Profiler & Developer Toolbar (built for Phalcon)

Prophiler - A PHP Profiler & Developer Toolbar built for Phalcon Demo The demo website has been moved to a separate repository: https://github.com/fab

this starter kite inspired by laravel & Geo and mvc pattern. it's wrap for Wordpress built in classes.

WordpressStarterKite Introduction Built With Prerequisite Directory Structure Guidelines Getting Started Authors Introduction this starter kite inspir

Pattern Lab Standard Edition for Twig

Pattern Lab Standard Edition for Twig The Standard Edition for Twig gives developers and designers a clean and stable base from which to develop a Twi

Comments
  • Abstract repository should implement an interface

    Abstract repository should implement an interface

    As far as I can tell, the main point of repositories is unit testability. (Otherwise, we'd just use the methods that phalcon provides for Models).

    In order to mock out the repos, we could use an interface instead of just and abstract class.

    opened by pabl0rg 1
Releases(v0.5.0)
  • v0.5.0(Jun 7, 2018)

  • v0.4.3(May 30, 2018)

  • v0.4.2(Apr 3, 2018)

  • v0.4.1(Mar 29, 2018)

    Improvements:

    • The count() and countBy() methods of the AbstractCollectionRepository now use MongoDB aggregation queries and are then much more efficient
    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Mar 29, 2018)

    New features:

    • implemented truncate() method in AbstractRepository

    Improvements:

    • Added missing documentation for getAggregate() method for AbstractCollectionRepository
    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Jul 7, 2017)

  • v0.3(Jul 7, 2017)

    New requirements:

    • PHP 7.1+
    • Phalcon 3.2+
    • Phalcon Incubator 3.2+

    New features and changes:

    • Added brand new AbstractCollectionRepository supporting MongoDB. Method list:

      • all()
      • find($id)
      • findOrFail($id)
      • first()
      • firstOrFail()
      • firstBy(array $where = [])
      • firstOrFailBy(array $where = [])
      • getBy(array $where = [])
      • getByLimit(int $limit, array $where = [])
      • getByOrder(string $orderBy, array $where = [], string $order = 'desc', int $limit = 0)
      • getIn(string $whereInKey, array $whereIn = [], string $orderBy = null, string $order = 'desc', int $limit = 0)
      • getNotIn(string $whereNotInKey, array $whereNotIn = [], string $orderBy = null, string $order = 'desc', int $limit = 0)
      • getInAndWhereByPage(int $page = 1, int $limit = 10, string $whereInKey = null, array $whereIn = [], $where = [], $orderBy = null, string $order = 'desc')
      • getByPage(int $page = 1, int $limit = 10, array $where = [], string $orderBy = null, string $order = 'desc')
      • create(array $inputs = [])
      • updateById($id, array $inputs)
      • destroy($id)
      • destroyFirstBy(array $where)
      • count()
      • countBy(array $where = [])
    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(May 23, 2017)

  • v0.2(May 10, 2017)

    New requirements:

    • PHP 7.0+
    • Phalcon 3.0+

    New features and changes:

    • Added new getInAndWhereByPage() method

    • The $where array parameter now allows for more complex queries. The following formats are now supported:

      • 'key' => 'value'

      Examples:

      $where = ['username' => 'Richard']
      
      • 'key' => ['value', 'operator']

      Examples:

      $where = ['age' => [30, '=']]
      $where = ['age' => [30, '<']]
      $where = ['age' => [30, '>']]
      $where = ['username' => ['%Fey%', 'LIKE']]
      
      • ['key1%OR%key2'] => ['value', 'operator']

      Examples:

      `$where = ['username%OR%description' => ['%Feynman%', 'LIKE']]`
      
    • Method parameters are now type hinted

    Source code(tar.gz)
    Source code(zip)
  • v0.1(Dec 11, 2016)

Owner
Michele Angioni
Technical Team Lead @takeaway
Michele Angioni
A Phalcon paginator adapter for Phalcon Collections

Phalcon Collection Paginator A Phalcon paginator adapter for Phalcon Collections Why create this? Being familiar with the various Pagination data adap

Angel S. Moreno 2 Oct 7, 2022
Simple repository pattern for laravel, with services!

With repository and service you can separate business logic and query logic, slim controller and DRY. Simple generate repository and service with artisan command, automatically bind interface with repository

Yaz3 27 Jan 1, 2023
Phalcon 3.x BB Debugger Strong and easy install.

Phalcon BB Debugger Phalcon Version: 3.x BB Debugger Version: 1.0.3 Change Log See ChangeLog What is BB Debugger ? The bb debugger, written for the ph

Ä°smail 6 Oct 7, 2022
Incubator adapters/functionality for the Phalcon PHP Framework

Phalcon Incubator This is a repository to publish/share/experiment with new adapters, prototypes or functionality that can potentially be incorporated

The Phalcon PHP Framework 735 Dec 27, 2022
CMS based on Phalcon PHP Framework with modular structure

Yona CMS Yona CMS - open source content management system (CMS). Written in Phalcon PHP Framework (version 3.x supported) Has a convenient modular str

Alexander Torosh 369 Dec 27, 2022
Invo - Sample application for the Phalcon PHP Framework

INVO Application Phalcon is a web framework delivered as a C extension providing high performance and lower resource consumption. This is a sample app

The Phalcon PHP Framework 344 Dec 14, 2022
Album-o-rama - Sample application for the Phalcon PHP Framework.

Album O'Rama Phalcon PHP is a web framework delivered as a C extension providing high performance and lower resource consumption. This is a sample app

The Phalcon PHP Framework 84 Oct 7, 2022
Implementation of an API application using the Phalcon Framework

phalcon-api Sample API using Phalcon Implementation of an API application using the Phalcon Framework https://phalcon.io Installation Clone the projec

The Phalcon PHP Framework 81 Dec 15, 2022
A powerful debug and profilers tool for the Phalcon Framework

Phalcon Debugbar Integrates PHP Debug Bar with Phalcon Framework. äø­ę–‡čÆ“ę˜Ž Features Normal request capturing Ajax request capturing Redirect request chain

Yajie Zhu 162 Oct 7, 2022
This is a Native PHP MVC. If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo.

Welcome to PHP-Native-MVC-Pattern ?? If you will build your own PHP project in MVC with router, you can clone this ready to use MVC pattern repo. Work

null 2 Jun 6, 2022