Download the PHP package stellarwp/models without Composer
On this page you can find all versions of the php package stellarwp/models. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download stellarwp/models
More information about stellarwp/models
Files in stellarwp/models
Package models
Short Description A library for a simple model structure.
License GPL-3.0-or-later
Homepage https://github.com/stellarwp/models
Informations about the package models
StellarWP Models
A library for a simple model structure.
Table of Contents
- Installation
- Notes on examples
- Configuration
- Creating a model
- Interacting with a model
- Attribute validation
- Data transfer objects
- Classes of note
- Model
- ModelQueryBuilder
- DataTransferObject
- Repositories\Repository
- Contracts of note
- Contracts\ModelPersistable
- Repositories\Contracts\Deletable
- Repositories\Contracts\Insertable
- Repositories\Contracts\Updatable
Installation
It's recommended that you install Schema as a project dependency via Composer:
We actually recommend that this library gets included in your project using Strauss.
Luckily, adding Strauss to your
composer.jsonis only slightly more complicated than adding a typical dependency, so checkout our strauss docs.
Notes on examples
Since the recommendation is to use Strauss to prefix this library's namespaces, all examples will be using the Boomshakalaka namespace prefix.
Configuration
This library requires some configuration before its classes can be used. The configuration is done via the Config class.
Creating a model
Models are classes that hold data and provide some helper methods for interacting with that data.
A simple model
This is an example of a model that just holds properties. Properties can be defined in one or both of the following ways:
Using the shorthand syntax:
Using property definitions for more control:
Property definition options:
type(string ...$types)- Set one or more types (int, string, bool, float, array, or class names)default($value)- Set a default value (can be a closure)nullable()- Allow null valuesrequired()- Property must be provided during constructionrequiredOnSave()- Property must be set before savingreadonly()- Property can only be set during construction, cannot be modified afterwardcastWith(callable $callback)- Custom casting function for the property value
A persistable model
This is a model that includes persistence operations (create, find, save, delete). Ideally, the actual persistence operations should be deferred to and handled by
a repository class, but the model should provide a simple interface for interacting with the repository. We get a persistable
model by implementing the Contracts\ModelPersistable contract.
Interacting with a model
Change tracking
Models track changes to their properties and provide methods to manage those changes:
Checking if properties are set
The isSet() method checks if a property has been set. This is different from PHP's isset() because it considers null values and default values as "set":
Key differences from PHP's isset():
isSet()returnstruefor properties with default valuesisSet()returnstruefor properties explicitly set tonullisSet()returnsfalseonly for properties that have no default and haven't been assigned
Creating models from query data
Models can be created from database query results using the fromData() method:
Build modes:
BUILD_MODE_STRICT: Throws exceptions for missing or extra propertiesBUILD_MODE_IGNORE_MISSING: Ignores properties missing from the dataBUILD_MODE_IGNORE_EXTRA: Ignores extra properties in the data (default)
Readonly properties
Properties marked as readonly() can only be set during construction and cannot be modified afterward:
Readonly properties are useful for:
- Primary keys that shouldn't change after creation
- Timestamps that are set once
- Any immutable identifiers or values
Extending model construction
Models can perform custom initialization after construction by overriding the afterConstruct() method:
Model Relationships
Models can define relationships to other models, similar to how properties are defined. Relationships support lazy loading and caching.
Defining Relationships
Relationships can be defined using either shorthand syntax or the fluent ModelRelationshipDefinition API:
Using shorthand syntax:
Using relationship definitions for more control:
Relationship Types
Five relationship types are available:
Relationship::HAS_ONE- Model has one related modelRelationship::HAS_MANY- Model has many related modelsRelationship::BELONGS_TO- Model belongs to another modelRelationship::BELONGS_TO_MANY- Model belongs to many related modelsRelationship::MANY_TO_MANY- Many-to-many relationship
Accessing Relationships
Relationships are loaded lazily when accessed as properties:
Relationship Caching
By default, relationships are cached after the first load. You can control caching behavior:
Managing Relationship Cache
Models provide methods to manage relationship caching:
Customizing Relationship Loading
Override the fetchRelationship() method to customize how relationships are loaded:
Attribute validation
Sometimes it would be helpful to validate attributes that are set in the model. To do that, you can create validate_*()
methods that will execute any time an attribute is set.
Here's an example:
Data Transfer Objects
Data Transfer Objects (DTOs) are classes that help with the translation of database query results (or other sources of data)
into models. DTOs are not required for using this library, but they are recommended. Using these objects helps you be more
deliberate with your query usage and allows your models and repositories well with the ModelQueryBuilder.
Here's an example of a DTO for breakfasts:
Repositories
Repositories are classes that fetch from and interact with the database. Ideally, repositories would be used to
query the database in different ways and return corresponding models. With this library, we provide
Deletable, Insertable, and Updatable contracts that can be used to indicate what operations a repository provides.
You may be wondering why there isn't a Findable or Readable contract (or similar). That's because the fetching needs
of a repository varies with the usecase. However, in the Repository abstract class, there is an abstract prepareQuery()
method. This method should return a ModelQueryBuilder instance that can be used to fetch data from the database.
Interacting with the Repository
Querying
Inserting
Updating
Deleting
Unsetting properties
Classes of note
Model
This is an abstract class to extend for your models.
ModelQueryBuilder
This class extends the stellarwp/db QueryBuilder class so that it returns
model instances rather than arrays or stdClass instances.
DataTransferObject
This is an abstract class to extend for your DTOs.
Repositories\Repository
This is an abstract class to extend for your repositories.
Contracts of note
Contracts\ModelPersistable
Provides definitions of methods for persistence operations in a model (create, find, save, delete, query).
Repositories\Contracts\Deletable
Provides method signatures for delete methods in a repository.
Repositories\Contracts\Insertable
Provides method signatures for insert methods in a repository.
Repositories\Contracts\Updatable
Provides method signatures for update methods in a repository.