Value object in scaffold. What it can be used for?



  • Thank u for your amazing project.
    I'm diving more and more inside of it and trying to understand it more deeply.
    In all the tutorials and videos there is explanation about creating a model by scaffolding. And in all the examples the field Value object name left empty. And Im wondering... What it can be used for? As i c, in most of the time Im enough with a model and its fields, but Im sure u guys put some kind a functionality in this Value object and it can be helpful in some situations.
    Can u say smth about it? Or maybe its already written somewhere, just i was not aware enough to find it.


  • Global Moderator

    Value Object in general are usually small immutable class that is used in Domain-Driven Design.
    It's usually used to address some sort of primitive work with data and being immutable(no setters) you can only change values on it upon creation, so you can discard it anytime or create new one any time you need.
    Kind of hard to explain in full, you'll just have to read it up (this one explains it very good and provides examples DDD VO).

    Basically you can do all of this in your controller, but that would be considered bad design.
    AsgardCms has similar approach in type of Presenters, basically you can achieve same effect.

    Lets say we have module for user profile and we need to do work on email. For one simple function you would use Accessors & Mutators of laravel (for example combine first name and last name).

    final class EmailAddress
    {
       private $address;
    
       public function __construct($address)
       {
           if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
               throw new InvalidArgumentException(sprintf('"%s" is not a valid email', $address));
           }
    
           $this->address = $address;
       }
    
       public function __toString()
       {
           return $this->address;
       }
    
       public function equals(EmailAddress $address)
       {
           return strtolower((string) $this) === strtolower((string) $address);
       }
    }
    
    // Allow email only if it's new one
    $oldUserEmail = new EmailAdrress('myoldemail@example.com');
    $newUserEmail = new EmailAdrress('mynewemail@example.com');
    $emailsEqual = $newUserEmail->equals($oldUserEmail); // false
    

    I know it's quite rough, but can be used for many good things.



  • @armababy - Thanks for the very useful explaination!
    This is something I've often felt like I wanted to have but never could argument (towards myself) that it justifies a class of it's own. But obviously - I was completely wrong ^^

    Cheers!

    This is my opinion at the moment!
    I hope to be able to change it as I grow more beard.

    0

Log in to reply