AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 3.x

    • How to install
  • Config

    • Configuration Loader
  • Container

    • IoC Service Container
  • Dto

    • Data Transfer Object (DTO)
    • Create Interface
    • Implement DTO
    • Property overloading
    • Populate
    • Json
    • Nested DTOs
    • Array DTO
  • Http

    • Introduction
    • Http Clients
  • Properties

    • Properties Overload
  • Support

    • Support Introduction
    • Laravel Aware Of Helpers
    • Aware Of Properties
    • Aware-Of Component Generator
  • Testing

    • Testing Introduction
    • Laravel
    • Test Cases
    • Traits
  • Utils

    • Populate
    • Json
You are viewing documentation for an outdated version. It is no longer supported!

Populate

Populatable objects

Should you require a uniform way to populate (hydrate) your objects, e.g. a model or a dto, then the Populatable interface is a good way to go. The populate() method allows you to hydrate your object using an array.

use Aedart\Contracts\Utils\Populatable;

class Box implements Populatable
{
    public function populate(array $data = []) : void
    {
        foreach($data as $name => $value){
            // Populate your object... not shown here
        }
    }
}

Verify Required Properties

A quick way to ensure that your objects are populated with the correct properties, is by using the verifyRequired() method, via the PopulateHelper. It will automatically throw an \Exception, in case that a required property is missing.

State the name of the required properties, as the 2nd argument for the verifyRequired() method.

use Aedart\Contracts\Utils\Populatable;
use Aedart\Utils\Helpers\PopulateHelper;

class Box implements Populatable
{
    public function populate(array $data = []) : void
    {
        // Fail if "width" and "height" properties are missing
        PopulateHelper::verifyRequired($data, [
            'width',
            'height'
        ]);
        
        // Do something with data.
    }
}

Warning

verifyRequired() is not intended to be a saturated validation method for input. Please consider using a Validator, if you plan to populate objects with data received from a request or other untrusted source.

Edit page
Last Updated: 08/02/2020, 09:56
Contributors: Alin Eugen Deac
Next
Json