PHP code example of stellarwp / models

1. Go to this page and download the library: Download stellarwp/models library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

stellarwp / models example snippets


use Boomshakalaka\StellarWP\Models\Config;

add_action( 'plugins_loaded', function() {
	Config::setHookPrefix( 'boom-shakalaka' );
} );

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Model;

class Breakfast_Model extends Model {
	/**
	 * @inheritDoc
	 */
	protected static $properties = [
		'id'        => 'int',
		'name'      => ['string', 'Default Name'], // With default value
		'price'     => 'float',
		'num_eggs'  => 'int',
		'has_bacon' => 'bool',
	];
}

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Model;
use Boomshakalaka\StellarWP\Models\ModelPropertyDefinition;

class Breakfast_Model extends Model {
	/**
	 * @inheritDoc
	 */
	protected static function properties(): array {
		return [
			'id' => ModelPropertyDefinition::create()
				->type('int')
				->

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\ModelPersistable {
	/**
	 * @inheritDoc
	 */
	protected static $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 )->prepareQuery();
	}
}

$breakfast = new Breakfast_Model([
	'name' => 'Original Name',
	'price' => 5.99,
]);

// Check if a property is dirty (changed)
$breakfast->setAttribute('name', 'New Name');
if ($breakfast->isDirty('name')) {
	echo 'Name has changed!';
}

// Get all dirty values
$dirtyValues = $breakfast->getDirty(); // ['name' => 'New Name']

// Commit changes (makes current values the "original")
$breakfast->commitChanges();
// or use the alias:
$breakfast->syncOriginal();

// Revert a specific property change
$breakfast->setAttribute('price', 7.99);
$breakfast->revertChange('price'); // price is back to 5.99

// Revert all changes
$breakfast->setAttribute('name', 'Another Name');
$breakfast->setAttribute('price', 8.99);
$breakfast->revertChanges(); // All properties back to original

// Get original value
$originalName = $breakfast->getOriginal('name');
$allOriginal = $breakfast->getOriginal(); // Get all original values

$breakfast = new Breakfast_Model();

// Properties with defaults are considered set
if ($breakfast->isSet('name')) { // true if 'name' has a default value
    echo 'Name is set';
}

// Properties without defaults are not set until assigned
if (!$breakfast->isSet('price')) { // false - no default and not assigned
    echo 'Price is not set';
}

// Setting a property to null still counts as set
$breakfast->setAttribute('price', null);
if ($breakfast->isSet('price')) { // true - explicitly set to null
    echo 'Price is set (even though it\'s null)';
}

// PHP's isset() behaves differently with null
if (!isset($breakfast->price)) { // false - isset() returns false for null
    echo 'PHP isset() returns false for null values';
}

// From an object or array
$data = DB::get_row("SELECT * FROM breakfasts WHERE id = 1");
$breakfast = Breakfast_Model::fromData($data);

// With different build modes
$breakfast = Breakfast_Model::fromData($data, Breakfast_Model::BUILD_MODE_STRICT);
$breakfast = Breakfast_Model::fromData($data, Breakfast_Model::BUILD_MODE_IGNORE_MISSING);
$breakfast = Breakfast_Model::fromData($data, Breakfast_Model::BUILD_MODE_IGNORE_EXTRA);

use Boomshakalaka\StellarWP\Models\Model;
use Boomshakalaka\StellarWP\Models\ModelPropertyDefinition;

class User_Model extends Model {
	protected static function properties(): array {
		return [
			'id' => ModelPropertyDefinition::create()
				->type('int')
				->readonly(), // Can only be set during construction
			'email' => ModelPropertyDefinition::create()
				->type('string'),
		];
	}
}

// Set readonly property during construction
$user = new User_Model(['id' => 1, 'email' => '[email protected]']);

// This works fine
$user->setAttribute('email', '[email protected]');

// This throws ReadOnlyPropertyException
$user->setAttribute('id', 2); // Error: Cannot modify readonly property "id"

// This also throws ReadOnlyPropertyException
unset($user->id); // Error: Cannot unset readonly property "id"

class Breakfast_Model extends Model {
	protected function afterConstruct() {
		// Perform custom initialization
		if ($this->has_bacon && $this->num_eggs > 2) {
			$this->setAttribute('name', $this->name . ' (Hearty!)');
		}
	}
}

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Model;
use Boomshakalaka\StellarWP\Models\ValueObjects\Relationship;

class Product_Model extends Model {
	/**
	 * @inheritDoc
	 */
	protected static $relationships = [
		'category' => Relationship::BELONGS_TO,
		'reviews' => Relationship::HAS_MANY,
		'tags' => Relationship::MANY_TO_MANY,
	];

	/**
	 * Define how to load the category relationship.
	 */
	protected function category() {
		return Category_Model::query()->where('id', $this->category_id);
	}

	/**
	 * Define how to load the reviews relationship.
	 */
	protected function reviews() {
		return Review_Model::query()->where('product_id', $this->id);
	}

	/**
	 * Define how to load the tags relationship.
	 */
	protected function tags() {
		return Tag_Model::query()
			->select('tags.*')
			->join('product_tags', 'product_tags.tag_id', 'tags.id')
			->where('product_tags.product_id', $this->id);
	}
}

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Model;
use Boomshakalaka\StellarWP\Models\ModelRelationshipDefinition;

class Product_Model extends Model {
	/**
	 * @inheritDoc
	 */
	protected static function relationships(): array {
		return [
			'category' => (new ModelRelationshipDefinition('category'))
				->belongsTo(),
			'reviews' => (new ModelRelationshipDefinition('reviews'))
				->hasMany(),
			'tags' => (new ModelRelationshipDefinition('tags'))
				->manyToMany()
				->disableCaching(), // Don't cache this relationship
		];
	}

	// Define relationship loaders as above...
}

$product = Product_Model::find(1);

// First access loads from database and caches result
$category = $product->category;

// Subsequent accesses use cached value (if caching enabled)
$category = $product->category; // No additional query

// Access multiple relationship
$reviews = $product->reviews; // Returns array of Review_Model instances

class Product_Model extends Model {
	protected static function relationships(): array {
		return [
			// Cached (default)
			'category' => (new ModelRelationshipDefinition('category'))
				->belongsTo(),

			// Not cached - always loads fresh
			'stock' => (new ModelRelationshipDefinition('stock'))
				->hasOne()
				->disableCaching(),
		];
	}
}

$product = Product_Model::find(1);

// Manually set a cached relationship value
$product->setCachedRelationship('category', $newCategory);

// Clear a specific relationship cache
$product->purgeRelationship('category');
$category = $product->category; // Reloads from database

// Clear all relationship caches
$product->purgeRelationshipCache();

class Product_Model extends Model {
	/**
	 * Custom relationship loading logic.
	 */
	protected function fetchRelationship(string $key) {
		// Add custom logic before loading
		if ($key === 'category' && !$this->category_id) {
			return null;
		}

		// Default loading behavior
		return parent::fetchRelationship($key);
	}
}

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Model;

class Breakfast_Model extends Model {
	/**
	 * @inheritDoc
	 */
	protected static $properties = [
		'id'        => 'int',
		'name'      => 'string',
		'price'     => 'float',
		'num_eggs'  => 'int',
		'has_bacon' => 'bool',
	];

	/**
	 * Validate the name.
	 *
	 * @param string $value
	 *
	 * @return bool
	 */
	public function validate_name( $value ): bool {
		if ( ! preg_match( '/eggs/i', $value ) ) {
			throw new \Exception( 'Breakfasts must have "eggs" in the name!' );
		}

		return true;
	}
}


namespace Boomshakalaka\Whatever;

use Boomshakalaka\Whatever\StellarWP\Models\DataTransferObject;
use Boomshakalaka\Whatever\Breakfast_Model;

class Breakfast_DTO extends DataTransferObject {
	/**
	 * Breakfast ID.
	 *
	 * @var int
	 */
	 public int $id;

	/**
	 * Breakfast name.
	 *
	 * @var string
	 */
	 public string $name;

	/**
	 * Breakfast price.
	 *
	 * @var float
	 */
	 public float $price;

	/**
	 * Number of eggs in the breakfast.
	 *
	 * @var int
	 */
	 public int $num_eggs;

	/**
	 * Whether or not the breakfast has bacon.
	 *
	 * @var bool
	 */
	 public bool $has_bacon;

	/**
	 * Builds a new DTO from an object.
	 *
	 * @since TBD
	 *
	 * @param object $object The object to build the DTO from.
	 *
	 * @return Breakfast_DTO The DTO instance.
	 */
	public static function fromObject( $object ): self {
		$self = new self();

		$self->id        = $object->id;
		$self->name      = $object->name;
		$self->price     = $object->price;
		$self->num_eggs  = $object->num_eggs;
		$self->has_bacon = (bool) $object->has_bacon;

		return $self;
	}

	/**
	 * Builds a model instance from the DTO.
	 *
	 * @since TBD
	 *
	 * @return Breakfast_Model The model instance.
	 */
	public function toModel(): Breakfast_Model {
		$attributes = get_object_vars( $this );

		return new Breakfast_Model( $attributes );
	}
}

namespace Boomshakalaka\Whatever;

use Boomshakalaka\StellarWP\Models\Contracts\Model;
use Boomshakalaka\StellarWP\Models\ModelQueryBuilder;
use Boomshakalaka\StellarWP\Repositories\Repository;
use Boomshakalaka\StellarWP\Repositories\Contracts;
use Boomshakalaka\Whatever\Breakfast_Model;
use Boomshakalaka\Whatever\Breakfast as Table;

class Breakfast_Repository extends Repository implements Contracts\Deletable, Contracts\Insertable, Contracts\Updatable {
	/**
	 * {@inheritDoc}
	 */
	public function delete( Model $model ): bool {
		return (bool) DB::delete( Table::table_name(), [ 'id' => $model->id ], [ '%d' ] );
	}

	/**
	 * {@inheritDoc}
	 */
	public function insert( Model $model ): Breakfast_Model {
		DB::insert( Table::table_name(), [
			'name' => $model->name,
			'price' => $model->price,
			'num_eggs' => $model->num_eggs,
			'has_bacon' => (int) $model->has_bacon,
		], [
			'%s',
			'%s',
			'%d',
			'%d',
		] );

		$model->id = DB::last_insert_id();

		return $model;
	}

	/**
	 * {@inheritDoc}
	 */
	function prepareQuery(): ModelQueryBuilder {
		$builder = new ModelQueryBuilder( Breakfast_Model::class );

		return $builder->from( Table::table_name( false ) );
	}

	/**
	 * {@inheritDoc}
	 */
	public function update( Model $model ): Model {
		DB::update( Table::table_name(), [
			'name' => $model->name,
			'price' => $model->price,
			'num_eggs' => $model->num_eggs,
			'has_bacon' => (int) $model->has_bacon,
		], [ 'id' => $model->id ], [
			'%s',
			'%s',
			'%d',
			'%d',
		], [ '%d' ] );

		return $model;
	}

	/**
	 * Finds a Breakfast by its ID.
	 *
	 * @since TBD
	 *
	 * @param int $id The ID of the Breakfast to find.
	 *
	 * @return Breakfast_Model|null The Breakfast model instance, or null if not found.
	 */
	public function find_by_id( int $id ): ?Breakfast_Model {
		return $this->prepareQuery()->where( 'id', $id )->get();
	}
}

$breakfast = App::get( Breakfast_Repository::class )->find_by_id( 1 );

// Or, we can fetch via the model, which defers to the repository.
$breakfast = Breakfast_Model::find( 1 );

$breakfast = new Breakfast_Model( [
	'name'      => 'Bacon and Eggs',
	'price'     => 5.99,
	'num_eggs'  => 2,
	'has_bacon' => true,
] );

$breakfast->save();

$breakfast = Breakfast_Model::find( 1 );
$breakfast->setAttribute( 'price', 6.99 );
$breakfast->save();

$breakfast = Breakfast_Model::find( 1 );
$breakfast->delete();

$breakfast = Breakfast_Model::find( 1 );
unset($breakfast->price); // Unsets the price property