Skip to content

Working with Repository

Yo-An Lin edited this page Apr 11, 2017 · 12 revisions

Creating Repository instance

A repository consists of a connection for READ, a connection for WRITE and the related table information.

Each schema has its own repo class, which is generated by the schema generator. And this is for getting pre-built constants like SQL statements, table name constants, column names faster.

To create a Repository of Book schema, simply call masterRepo static method on Book class:

$repo = Book::masterRepo();

The above code creates an instance of BookRepo with connections to the master database.

To customize the repository connection, like separating read/write connections, you can simply pass Maghead\Connection instances:

$repo = Book::repo($write, $read);

If $read is omit, then the read connection will be same as $write:

$repo = Book::repo($write);

Generally, if you don't need to customize the connections, calling ::masterRepo will be faster than ::repo since it doesn't check the parameter types.

Creating records

  • BaseRepo::create(array $args) : Maghead\Runtime\Result

    To create a record, simply call ::create.

      $ret = Book::masterRepo()->create([
          'title' => 'Programming PHP',
      ]);
    

    This method returns Maghead\Runtime\Result object.

Finding records

  • BaseRepo::findWith(array $conditions)

    Find the record base on the condition array.

  • BaseRepo::findByPrimaryKey($key)

    Find the record by the given primary key.

  • BaseRepo::findByKeys(array $conditions, array $keys)

    Find the record base on the condition array, the condition array will be filtered by the keys. This method calls ::findWith with the filtered condition array.

  • BaseRepo::load($condition)

    Find the record base on either primary key or a condition array.

    Note: this method is slower than findWith or findByPrimaryKey if you know what will be used to find the record.

  • BaseRepo::loadForUpdate($condition)

    Find the record base on either primary key or a condition array.

    This method executes SQL query with SELECT ... FOR UPDATE syntax to provide the row-level lock for the selected row.

    Note: this method is only supported for MySQL.

Creating query objects from Repository

After you created an instance of Repository for one schema, you can create query objects from it to customize your query rather than the simple CRUD operation for just one record object.

Currently Maghead supports 3 basic query factory methods:

  1. BaseRepo::select($sel)
  2. BaseRepo::update($data)
  3. BaseRepo::delete()

Clone this wiki locally