Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 30 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ There are so many advanced options documented below. Sold? Let's install.
- [Multiple Selects](#multiple-selects)
- [Select Distinct](#select-distinct)
- [Get All](#get-all)
- [Chunk](#chunk)
- [Get First Row](#get-first-row)
- [Get Rows Count](#get-rows-count)
- [**Where**](#where)
Expand Down Expand Up @@ -95,7 +96,7 @@ ___


## Connection
WP Fluent supports multiple database connections but you can use alias
WP Fluent supports multiple database connections but you can use alias
for only one connection at a time. Just pass the global wpdb and
necessary configurations during connection.

Expand All @@ -120,12 +121,12 @@ When you create a connection:
new \WpFluent\Connection($wpdb, ['prefix' => $wpdb->prefix], 'MyAlias');
```
`MyAlias` is the name for the class alias you want to use e.g. `MyAlias::table(...)`

You can use any name (with Namespace also, `MyNamespace\\MyClass`) you like or
you may skip it if you don't need an alias. Alias gives you the ability
to easily access the QueryBuilder class across your application.

When not using an alias you can instantiate the QueryBuilder handler
When not using an alias you can instantiate the QueryBuilder handler
separately, helpful for Dependency Injection and Testing.

```PHP
Expand All @@ -152,7 +153,7 @@ The query below returns the first row where id = 3, `null` if no rows.
```PHP
$row = DB::table('my_table')->find(3);
```
Access your row like, `echo $row->name`. If your field name is not `id` then
Access your row like, `echo $row->name`. If your field name is not `id` then
pass the field name as second parameter `DB::table('my_table')->find(3, 'person_id');`

The query below returns all the rows where `name = 'Frost'`, `null` if no rows.
Expand All @@ -173,7 +174,7 @@ $query = DB::table('my_table')->select('*');
->select(array('mytable.myfield1', 'mytable.myfield2', 'another_table.myfield3'));
```

Using select method multiple times `select('a')->select('b')` will also select `a`
Using select method multiple times `select('a')->select('b')` will also select `a`
and `b`. It can be useful if you want to do conditional selects (within a PHP `if`).


Expand All @@ -196,6 +197,20 @@ foreach ($result as $row) {
}
```

#### Chunk
What if you have thousands of rows in your database? Using [Get All](#get-all), can fill your memory up when you load all that data.
Here is the chunk mehtod. You can provide a number of rows to fetch at once, and a callback to run on the result.

```PHP
$file = fopen("php://output", 'w');
$query = DB::table('my_table')->chunk(100, function ($records) use ($file) {
foreach($records as $record) {
fputcsv($file, $record);
}
});
fclose($file);
```

#### Get First Row
```PHP
$query = DB::table('my_table')->where('name', '=', 'admin');
Expand Down Expand Up @@ -262,7 +277,7 @@ DB::table('my_table')
->where('my_table.age', 10)
->where(function ($q) {
$q->where('name', 'LIKE', '%najrul%');

// You can provide a closure on these wheres too, to nest further.
$q->orWhere('description', 'LIKE', '%frost%');
});
Expand Down Expand Up @@ -485,7 +500,7 @@ $queryObj->getRawSql();
```

### Sub Queries and Nested Queries
Rarely but you may need to run sub queries or nested queries. WP Fluent is powerful
Rarely but you may need to run sub queries or nested queries. WP Fluent is powerful
enough to do this for you. You can create different query objects and use the
`DB::subQuery()` method.

Expand Down Expand Up @@ -543,7 +558,7 @@ so banned users don't get access.

The syntax is `registerEvent('event type', 'table name', action in a closure)`.

If you want the event to be performed when **any table is being queried**, provide
If you want the event to be performed when **any table is being queried**, provide
`':any'` as table name.

**Other examples:**
Expand All @@ -552,12 +567,12 @@ After inserting data into `my_table`, details will be inserted into another tabl
```PHP
DB::registerEvent('after-insert', 'my_table', function ($queryBuilder, $insertId) {
$data = array('person_id' => $insertId, 'details' => 'Meh', 'age' => 5);

$queryBuilder->table('person_details')->insert($data);
});
```

Whenever data is inserted into `person_details` table, set the timestamp field
Whenever data is inserted into `person_details` table, set the timestamp field
`created_at`, so we don't have to specify it everywhere:
```PHP
DB::registerEvent('after-insert', 'person_details', function ($queryBuilder, $insertId) {
Expand All @@ -573,21 +588,21 @@ After deleting from `my_table` delete the relations:
```PHP
DB::registerEvent('after-delete', 'my_table', function ($queryBuilder, $queryObject) {
$bindings = $queryObject->getBindings();

$queryBuilder->table('person_details')->where('person_id', $binding[0])->delete();
});
```


WP Fluent passes the current instance of query builder as first parameter of your
closure so you can build queries with this object, you can do anything like usual
closure so you can build queries with this object, you can do anything like usual
query builder (`DB`).

If something other than `null` is returned from the `before-*` query handler, the value
will be result of execution and DB will not be actually queried (and thus, corresponding
`after-*` handler will not be called either).

Only on `after-*` events you get three parameters: **first** is the query builder,
Only on `after-*` events you get three parameters: **first** is the query builder,
**third** is the execution time as float and **the second** varies:

- On `after-select` you get the `results` obtained from `select`.
Expand Down Expand Up @@ -615,8 +630,8 @@ Here are some cases where Query Events can be extremely helpful:
- Add/edit created_at and updated _at data after each entry.

#### Notes
- Query Events go recursively, for example after inserting into `table_a` your event
inserts into `table_b`, now you can have another event registered with `table_b`
- Query Events go recursively, for example after inserting into `table_a` your event
inserts into `table_b`, now you can have another event registered with `table_b`
which inserts into `table_c`.
- Of course Query Events don't work with raw queries.
- **This is forked from awesome @usmanhalalit vai's [Pixie](https://github.com/usmanhalalit/pixie)
Expand Down
27 changes: 25 additions & 2 deletions src/QueryBuilder/QueryBuilderHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ public function setFetchMode($mode)
*/
public function asObject($className, $constructorArgs = array())
{
var_dump('need to implement this'); die();
var_dump('need to implement this');
die();

return $this->setFetchMode(\PDO::FETCH_CLASS, $className, $constructorArgs);
}
Expand Down Expand Up @@ -282,7 +283,7 @@ public function getQuery($type = 'select', $dataToBePassed = array())
}

$queryArr = $this->adapterInstance->$type($this->statements, $dataToBePassed);

return $this->container->build(
'\\WpFluent\\QueryBuilder\\QueryObject',
array($queryArr['sql'], $queryArr['bindings'])
Expand Down Expand Up @@ -1151,4 +1152,26 @@ public function when($value, $callback, $default = null)

return $this;
}

/**
* Chunk query by given no of records and apply the callback with the records
*
* @param int $limit
* @param callable $callback

* @return mixed
*/
public function chunk($limit, $callback, $page = 1)
{
$offset = ($page - 1) * $limit;
$this->limit($limit)->offset($offset);

$records = $this->get();
if (count($records)) {
$callback($records);
return $this->chunk($limit, $callback, ++$page);
}

return $page;
}
}