PHP code example of redcrystal / cast

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

    

redcrystal / cast example snippets



namespace App\ValueObjects;

use RedCrystal\Cast\ValueObject;

class Email implements ValueObject
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function toScalar()
    {
        return $this->value;
    }

    public function __toString() {
        return $this->toScalar();
    }
}



namespace App;

use App\ValueObjects\Email;
use Illuminate\Database\Eloquent\Model;
use RedCrystal\Cast\CastsValueObjects;

class User extends extends Model {
	use CastsValueObjects;

	
	protected $objects = [
		// name of the attribute => name of the value object class
		'email' => Email::class
	];
	
	// ...
}

$user = User::find($id);

$user->email; // returns instance of App\ValueObjects\Email
$user->email->toScalar(); // "[email protected]"
(string) $user->email; // "[email protected]"

$user = new User();

$user->email = "[email protected]";
$user->email = new Email("[email protected]");