taeluf/rdb

Custom property getters on beans, better error reporting, sql-verbs as an API. And some other quality of life stuff.

0.2.1 2021-02-06 17:56 UTC

This package is auto-updated.

Last update: 2024-10-09 05:48:44 UTC


README

Custom property getters on beans, better error reporting, sql-verbs as an API. Additional convenienence functions.

Getting Started

Install: composer require taeluf/rdb 0.2.* or v0.2.x-dev or {"require":{"taeluf/rdb": "0.2.*"}}

We use \RDB:: instead of \R::. See Redbean docs for things not covered here.

1. Setup your connection

// \RDB::setup('mysql:host=localhost;dbname=mydatabase', 'user', 'password' );  
\RDB::setup('sqlite:'.__DIR__.'/testdb.sqlite');  
//empty our recipe table at start of each test  
\RDB::delete('recipe',[]);  

2. Write Some Data

\RDB::insert('recipe', ['name'=>'Tofu Scramble']);// <- convenience method in RDB  
\RDB::insert('recipe', ['name'=>'Vege Stirfry']);   
$loMein = \RDB::insert('recipe', ['name'=>'Lo Mein']);//also returns a bean  
$loMein->description = "A non-authentic Chinese noodle dish";  
// \RDB::store($loMein); // <- The redbean way  
$loMein->save();   // <- Convenience method in RDB  
\RDB::update('recipe', ['id'=>$loMein->id,'name'=>'Veggie Lo Mein']); //<-- Convenience method in RDB. Updates based on the id  
\RDB::update('recipe', ['name'=>'Veggie Stirfry'], ['name'=>'Vege Stirfry']); //<-- 2nd array is used as WHERE params for the update   
  
$list = \RDB::select('recipe', ['name'=>'Veggie Lo Mein']);  
$loadedLoMein = $list[0];  
  
$list2 = \RDB::select('recipe', ['name'=>'Veggie Stirfry']);  
$loadedStirfry = $list2[0];  

3. Create a Model (if you need)

Custom Redbean Models let you add functionality to redbean. RDB simplifies some things.

// RDBModel namespace is required  
namespace RDBModel;  
  
class Recipe extends \RedBeanPHP\SimpleModel {  
  
    //Custom property getters MUST start with &get  
    public function &getSlug(){  
        $name = strtolower($this->name);  
        $parts = explode(' ', $name);  
        $slug = implode('-', $parts);  
        return $slug;  
    }  
}  

& Use that model:

$tofu  = \RDB::select('recipe', ['name'=>'Tofu Scramble'])[0];  
$slug = $tofu->slug; // <- not stored in db  
$url = '/recipe/'.$slug.'/';  
  
return true  
    && $this->compare('tofu-scramble', $slug)  
;  

Other Stuff

  • $bean->props() to get all properties (just the ones from the database)
  • $bean->export() adds _type to the exported array.
    • (untested) Call $bean->import($exported) and your exported array will load into the database, thanks to the _type addition
  • Table names (types) are made lower-case, and non alpha non-underscore characters are removed, so you don't have to be so careful about the type you pass into RDB::find()