A library for a simple model structure.
- Installation
- Notes on examples
- Configuration
- Creating a model
- Interacting with a model
- Data transfer objects
- Classes of note
- Contracts of note
It's recommended that you install Schema as a project dependency via Composer:
composer require stellarwp/models
We actually recommend that this library gets included in your project using Strauss.
Luckily, adding Strauss to your
composer.json
is only slightly more complicated than adding a typical dependency, so checkout our strauss docs.
Since the recommendation is to use Strauss to prefix this library's namespaces, all examples will be using the Boomshakalaka
namespace prefix.
This library requires some configuration before its classes can be used. The configuration is done via the Config
class.
use Boomshakalaka\StellarWP\Models\Config;
add_action( 'plugins_loaded', function() {
Config::setHookPrefix( 'boom-shakalaka' );
} );
Models are classes that hold data and provide some helper methods for interacting with that data.
This is an example of a model that just holds properties.
namespace Boomshakalaka\Whatever;
use Boomshakalaka\StellarWP\Models\Model;
class Breakfast_Model extends Model {
/**
* @inheritDoc
*/
protected $properties = [
'id' => 'int',
'name' => 'string',
'price' => 'float',
'num_eggs' => 'int',
'has_bacon' => 'bool',
];
}
namespace Boomshakalaka\Whatever;
use Boomshakalaka\StellarWP\Models\Contracts;
use Boomshakalaka\StellarWP\Models\Model;
use Boomshakalaka\StellarWP\Models\ModelQueryBuilder;
class Breakfast_Model extends Model implements Contracts\ModelCrud {
/**
* @inheritDoc
*/
protected $properties = [
'id' => 'int',
'name' => 'string',
'price' => 'float',
'num_eggs' => 'int',
'has_bacon' => 'bool',
];
/**
* @inheritDoc
*/
public static function create( array $attributes ) : Model {
$obj = new static( $attributes );
return App::get( Repository::class )->insert( $obj );
}
/**
* @inheritDoc
*/
public static function find( $id ) : Model {
return App::get( Repository::class )->get_by_id( $id );
}
/**
* @inheritDoc
*/
public function save() : Model {
return App::get( Repository::class )->update( $this );
}
/**
* @inheritDoc
*/
public function delete() : bool {
return App::get( Repository::class )->delete( $this );
}
/**
* @inheritDoc
*/
public static function query() : ModelQueryBuilder {
return App::get( Repository::class )->prepare_query();
}
}