PHP code example of esensi / model

1. Go to this page and download the library: Download esensi/model 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/ */

    

esensi / model example snippets




use Esensi\Model\Model;

class Post extends Model {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

}



use Esensi\Model\SoftModel;

class Post extends SoftModel {

}



use Esensi\Model\Contracts\ValidatingModelInterface;
use Esensi\Model\Traits\ValidatingModelTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Post extends Eloquent implements ValidatingModelInterface {

    use ValidatingModelTrait;

    /**
     * These are the default rules that the model will validate against.
     * Developers will probably want to specify generic validation rules
     * that would apply in any save operation vs. form or route
     * specific validation rules. For simple models, these rules can
     * apply to all save operations.
     *
     * @var array
     */
    protected $rules = [
       'title'     => [ 'max:64' ],
       'slug'      => [ 'max:16', 'alpha_dash', 'unique' ],
       'published' => [ 'boolean' ],
       // ... more attribute rules
    ];

    /**
     * These are the rulesets that the model will validate against
     * during specific save operations. Rulesets should be keyed
     * by either the in progress event name of the save operation
     * or a custom unique key for custom validation.
     *
     * The following rulesets are automatically applied during
     * corresponding save operations:
     *
     *     "creating" after "saving" but before save() is called (on new models)
     *     "updating" after "saving" but before save() is called (on existing models)
     *     "saving" before save() is called (and only if no "creating" or "updating")
     *     "deleting" when calling delete() method
     *     "restoring" when calling restore() method (on a soft-deleting model)
     *
     * @var array
     */
    protected $rulesets = [

        'creating' => [
            'title'     => [ '

Route::post( 'posts', function()
{
    // Hydrate the model from the Input
    $attributes = Input::only( 'title', 'slug', 'published' );
    $post = new Post( $attributes );

    // Attempt to save, will return false on invalid model.
    // Because this is a new model, the "creating" ruleset will
    // be used to validate against. If it does not exist then the
    // "saving" ruleset will be attempted. If that does not exist, then
    // finally it will default to the Post::$rules.
    if ( ! $post->save() )
    {
        // Redirect back to the form with the message bag of errors
        return Redirect::to( 'posts' )
            ->withErrors( $post->getErrors() )
            ->withInput();
    }

    // Redirect to the new post
    return Redirect::to( 'posts/' . $post->id );
});



use Esensi\Model\Contracts\PurgingModelInterface;
use Esensi\Model\Traits\PurgingModelTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Post extends Eloquent implements PurgingModelInterface {

    use PurgingModelTrait;

    /**
     * These are the attributes to purge before saving.
     *
     * Remember, anything prefixed with "_" or ending
     * in "_confirmation" will automatically be purged
     * and does not need to be listed here.
     *
     * @var array
     */
    protected $purgeable = [
        'analytics_id',
        '_private_attribute',
        'password_confirmation',
    ];

}

Route::post( 'posts', function( $id )
{
    // Hydrate the model from the Input
    $input = Input::all();
    $post = new Post($input);

    // At this point $post->analytics_id might exist.
    // If we tried to save it, MySQL would throw an error.

    // Save the Post
    $post->save();

    // At this point $post->analytics_id is for sure purged.
    // It was excluded becaused it existed in Post::$purgeable.
});

// Hydrate the model from the Input
$post = Post::find($id);
$post->fill( Input::all() );

// Manually purge attributes prior to save()
$post->purgeAttributes();

// Manually get the attributes
$post->getHashable(); // ['foo']

// Manually set the purgeable attributes
$post->setPurgeable( ['foo', 'bar'] ); // ['foo', 'bar']

// Manually add an attribute to the purgeable attributes
$post->addPurgeable( 'baz' ); // ['foo', 'bar', 'baz']
$post->mergePurgeable( ['zip'] ); // ['foo', 'bar', 'baz', 'zip']
$post->removePurgeable( 'foo' ); // ['bar', 'baz', 'zip']

// Check if an attribute is in the Post::$purgeable property
if ( $post->isPurgeable( 'foo' ) )
{
    // ... foo is not purgeable so this would not get executed
}

// Do not run purging for this save only.
// This is useful when purging is enabled
// but needs to be temporarily bypassed.
$post->saveWithoutPurging();

// Disable purging
$post->setPurging(false); // a value of true would enable it

// Run purging for this save only.
// This is useful when purging is disabled
// but needs to be temporarily ran while saving.
$post->saveWithPurging();



use Esensi\Model\Contracts\HashingModelInterface;
use Esensi\Model\Traits\HashingModelTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent implements HashingModelInterface {

    use HashingModelTrait;

    /**
     * These are the attributes to hash before saving.
     *
     * @var array
     */
    protected $hashable = [ 'password' ];

}

Route::post( 'account', function()
{
    // Hydrate the model from the Input
    $user = Auth::user();
    $user->password = Input::get('password');

    // At this point $user->password is still plain text.
    // This allows for the value to be checked by validation.

    // Save the User
    $user->save();

    // At this point $user->password is for sure hashed.
    // It was hashed becaused it existed in User::$hashable.
});

// Hydrate the model from the Input
$post = User::find($id);
$post->password = Input::get('password');

// Manually hash attributes prior to save()
$post->hashAttributes();

// Manually get the attributes
$post->getHashable(); // ['foo']

// Manually set the hashable attributes
$post->setHashable( ['foo', 'bar'] ); // ['foo', 'bar']

// Manually add an attribute to the hashable attributes
$post->addHashable( 'baz' ); // ['foo', 'bar', 'baz']
$post->mergeHashable( ['zip'] ); // ['foo', 'bar', 'baz', 'zip']
$post->removeHashable( 'foo' ); // ['bar', 'baz', 'zip']

// Check if an attribute is in the User::$hashable property
if ( $post->isHashable( 'foo' ) )
{
    // ... foo is not hashable so this would not get executed
}

// Check if an attribute is already hashed
if ( $post->isHashed( 'foo' ) )
{
    // ... if foo were hashed this would get executed
}

// Check if the password when hashed matches the stored password.
// This is just a unified shorthand to Crypt::checkHash().
if ( $post->checkHash( 'password123', $post->password ) )
{
    // ... if the password matches you could authenticate the user
}

// Swap out the HasherInterface used
$post->setHasher( new MyHasher() );

// Do not run hashing for this save only.
// This is useful when hashing is enabled
// but needs to be temporarily bypassed.
$post->saveWithoutHashing();

// Disable hashing
$post->setHashing(false); // a value of true would enable it

// Run hashing for this save only.
// This is useful when hashing is disabled
// but needs to be temporarily ran while saving.
$post->saveWithHashing();

// Hydrate the model from the Input
$post = Model::find($id);
$post->secret = Input::get('secret'); // automatically encrypted

// Manually encrypt attributes prior to save()
$post->encryptAttributes();

// Manually encrypt and decrypte a value
$encrypted = $post->encrypt( 'plain text' );
$decrypted = $post->decrypt( $encrypted ); // plain text

// Manually get the attributes
$post->getEncryptable(); // ['foo']

// Manually set the encryptable attributes
$post->setEncryptable( ['foo', 'bar'] ); // ['foo', 'bar']

// Manually add an attribute to the encryptable attributes
$post->addEncryptable( 'baz' ); // ['foo', 'bar', 'baz']
$post->mergeEncryptable( ['zip'] ); // ['foo', 'bar', 'baz', 'zip']
$post->removeEncryptable( 'foo' ); // ['bar', 'baz', 'zip']

// Check if an attribute is in the Model::$encryptable property
if ( $post->isEncryptable( 'foo' ) )
{
    // ... foo is not encryptable so this would not get executed
}

// Check if an attribute is already encrypted.
// You could also check $post->isDecrypted( 'foo' ).
if ( $post->isEncrypted( 'foo' ) )
{
    // ... if foo were encrypted this would get executed
}

// Swap out the encrypter class used
$post->setEncrypter( new MyEncrypter() );

// Disable encrypting
$post->setEncrypting(false); // a value of true would enable it



use Esensi\Model\Contracts\JugglingModelInterface;
use Esensi\Model\Traits\JugglingModelTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Post extends Eloquent implements JugglingModelInterface {

    use JugglingModelTrait;

    /**
     * Attributes to cast to a different type.
     *
     * @var array
     */
    protected $jugglable = [

        // Juggle the published_at attribute to a date
        'published_at' => 'date',

        // Cast the terms attribute to a boolean
        'terms' => 'boolean',

        // Juggle the foo attribute to a custom bar type
        'foo' => 'bar',
    ];

    /**
     * Example of a custom juggle "bar" type.
     *
     * @param  mixed $value
     * @return \Bar
     */
    protected function juggleBar( $value )
    {
        return new Bar($value);
    }

}

Route::post( 'post/{id}/publish', function( $id )
{
    // Hydrate the model from the Input
    $post = Post::find($id);

    // The published_at attribute will be converted to a Carbon date
    // object. You could then use $post->published_at->format('Y-m-d').
    $post->published_at = Input::get('published_at');

    // Convert those pesky checkboxes to proper booleans.
    $post->terms = Input::get('terms', false);

    // The foo attribute will be casted as the custom "bar" type using
    // juggleBar() so it's value would now be a Bar object.
    $post->foo = Input::get('foo');

    // Save the Post or do something else
    $post->save();
});

// Hydrate the model from the Input
$post = Model::find($id);
$post->foo = Input::get('foo'); // automatically juggled

// Manually juggle attributes after setting
$post->juggleAttributes();

// Manually juggle a value to a type
$boolean   = $post->juggle( 'true', 'boolean' ); // bool(true)
$boolean   = $post->juggleBoolean( '0' ); // bool(false)
$array     = $post->juggleArray( 'foo' ); // array(0 => foo)
$date      = $post->juggleDate( '2014-07-10' ); // object(\Carbon\Carbon)
$dateTime  = $post->juggleDateTime( Carbon::now() ); // string(2014-07-10 11:17:00)
$timestamp = $post->juggleTimestamp( '07/10/2014 11:17pm' ); // integer(1405034225)

// Manually get the attributes
$post->getJugglable(); // ['foo' => 'string']

// Manually set the jugglable attributes
$post->setJugglable( ['bar' => 'boolean'] ); // ['bar' => 'boolean']

// Manually add an attribute to the jugglable attributes
$post->addJugglable( 'baz', 'integer' ); // ['bar' => 'boolean', 'baz' => 'integer']
$post->mergeJugglable( ['zip' => 'array'] ); // ['bar' => 'boolean', 'baz' => 'integer', 'zip' => 'array']
$post->removeJugglable( 'bar' ); // ['baz' => 'integer', 'zip' => 'array']

// Check if an attribute is in the Model::$jugglable property
if ( $post->isJugglable( 'foo' ) )
{
    // ... foo is not jugglable so this would not get executed
}

// Check if a type is castable
// For this example juggleBar() is not a method.
if ( $post->isJuggleType( 'bar' ) )
{
    // ... this code wouldn't get executed because bar is not a cast type
}

// Throws an exception on invalid cast type
// It's used internally by setJugglable() to enforce valid cast types
$post->checkJuggleType( 'bar' );

// Disable juggling
$post->setJuggling(false); // a value of true would enable it



use Esensi\Model\Contracts\RelatingModelInterface;
use Esensi\Model\Traits\RelatingModelTrait;
use Illuminate\Database\Eloquent\Model as Eloquent;

class Post extends Eloquent implements RelatingModelInterface {

    use RelatingModelTrait;

    /**
     * These are the relationships that the model should set up.
     * Using PHP and Laravel's magic, these relationship keys
     * resolve to the actual models automatically.
     *
     * @example relationship bindings:
     *
     *     [ 'hasOne', 'related', 'foreignKey', 'localKey' ]
     *     [ 'hasMany', 'related', 'foreignKey', 'localKey' ]
     *     [ 'hasManyThrough', 'related', 'through', 'firstKey', 'secondKey' ]
     *     [ 'belongsTo', 'related', 'foreignKey', 'otherKey', 'relation' ]
     *     [ 'belongsToMany', 'related', 'table', 'foreignKey', 'otherKey', 'relation' ]
     *     [ 'morphOne', 'related', 'name', 'type', 'id', 'localKey' ]
     *     [ 'morphMany', 'related', 'name', 'type', 'id', 'localKey' ]
     *     [ 'morphTo', 'name', 'type', 'id' ]
     *     [ 'morphToMany', 'related', 'name', 'table', 'foreignKey', 'otherKey', 'inverse' ]
     *     [ 'morphedByMany', 'related', 'name', 'table', 'foreignKey', 'otherKey' ]
     *
     * @var array
     */
    protected $relationships = [

        // Bind Comment model as a hasMany relationship.
        // Use $post->comments to query the relationship.
        'comments' => [ 'hasMany', 'Comment' ],

        // Bind User model as a belongsTo relationship.
        // Use $post->author to get the User model.
        'author' => [ 'belongsTo', 'User' ],

        // Bind User model as a belongsTo relationship.
        // Use $post->author to get the User model.
        'tags' => [ 'belongsToMany', 'Tag']
    ];

    /**
     * These are the additional pivot attributes that the model
     * will setup on the relationships that support pivot tables.
     *
     * @var array
     */
    protected $relationshipPivots = [

        // Bind pivot attributes to Tag model when querying the relationship.
        // This is equivalent to $post->tags()->withTimestamps()->withPivot('foo').
        'tags' => [ 'timestamps', 'foo' ]
    ];
}

Route::get( 'posts/{id}/comments', function( $id )
{
    // Retrieve the post by ID
    $post = Post::find( $id );

    // Query the post for all the related comments.
    // The trait will resolve the "comments" from
    // the Post::$relationships bindings.
    $comments = $post->comments()->all();

    // It is also possible to shorten this using the
    // magic attributes instead. It is equivalent to
    // the above call.
    $comments = $post->comments;

    // Access the pivot table columns off a
    // many-to-many relationship model.
    $tag = $post->tags()->first();
    $carbon = $tag->pivot->created_at; // Carbon Date
    $bar = $tag->pivot->foo;
});