Skip to content

[Proposal] Decouple mutators / attribute casting from the Eloquent ORM #16377

Closed
@andrzejkupczyk

Description

Wouldn't be great to encapsulate the attributes manipulation? That could be very useful eg. in the Request class. Regarding casting I thought of something as simple as:

  • CastableContract
  • CastableTrait
abstract class Model implements ArrayAccess, Arrayable, Castable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{
    use CastableTrait;
    …
}
class Request extends SymfonyRequest implements Arrayable, ArrayAccess, Castable
{
    use CastableTrait, Macroable;
    …
}

In combination with custom casting discussed in #16305 and #13706 it could be a very powerfull and yet a clean solution. Another approach could be a Processor/Transformer implementation (this is just a basic idea inspired by the need to encapsulate request data processing):

  • Processable contract
interface Processable
{
    /**
     * Get the processed contents of the object.
     *
     * @return mixed
     */
    public function processed();
}
  • an object/array could be also easily processed with a processor composite:
class ProcessableStack extends \SplObjectStorage implements Processable
{
    /**
     * Calculates an unique identifier for the contained processor.
     *
     * @param Processor $object
     *
     * @return string
     */
    public function getHash($object): string
    {
        return get_class($object);
    }

    /**
     * {@inheritdoc}
     */
    public function processed()
    {
        if (!$input = func_get_arg(0)) {
            return;
        }

        foreach ($this as $hash => $processor) {
            $input = $processor->run($input);
        }

        return $input;
    }
}
  • examples of use:
$request->processedWith(UserUpdateRequest::class);
// or
$request->setProcessor(new UserUpdateRequest)->processed();
// or
$request->processed();

or maybe better interally by all(), input(), except() etc.?

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions