ObjectCopyTrait
The ObjectCopyTrait provides an implementation of the ObjectCopyInterface methods that can be used in your classes.
Overview
This trait implements:
copyFrom()- Copies properties from a source object to the current objectcopyTo()- Copies properties from the current object to a target object
Both methods use the static ObjectCopy::copy() method internally.
Usage
To use the trait in your class:
use ByJG\Serializer\ObjectCopyInterface;
use ByJG\Serializer\ObjectCopyTrait;
class User implements ObjectCopyInterface
{
use ObjectCopyTrait;
public $id;
public $name;
public $email;
// The class now has copyFrom() and copyTo() methods
}
Example
// Creating an object and copying properties from an array
$user = new User();
$user->copyFrom([
'id' => 1,
'name' => 'John Doe',
'email' => '[email protected]'
]);
// Copying properties to another object
$userData = new stdClass();
$user->copyTo($userData);
Property handlers can be used with these methods for property transformation. For detailed documentation, see the Property Handlers Guide.
Benefits of using the trait
- Implementing the interface: Your class automatically fulfills the
ObjectCopyInterfacecontract - Code reuse: You don't need to implement the copy logic in each class
- Consistency: All classes using the trait will handle copying in the same way
- Flexibility: You can still use property handlers for transformations
When to use ObjectCopyTrait vs. BaseModel
- Use
ObjectCopyTraitwhen you want to add copy functionality to a class that already extends another class - Use
BaseModelwhen you want a ready-to-use base class that includes copying functionality plus other utility methods
Related Components
- ObjectCopyInterface - Interface defining the copy methods
- ObjectCopy - Utility class for copying properties between objects
- BaseModel - Abstract base class using this trait