Skip to content

Instantly share code, notes, and snippets.

@HichemTab-tech
Last active August 29, 2023 21:57
Show Gist options
  • Save HichemTab-tech/96c6e2e6414379c8fad5afcbe0ceae34 to your computer and use it in GitHub Desktop.
Save HichemTab-tech/96c6e2e6414379c8fad5afcbe0ceae34 to your computer and use it in GitHub Desktop.
BaseSetGetClass: Simplify property handling in PHP classes by extending this class. Automatically generates setters and getters, enabling concise property manipulation.

BaseSetGetClass

The BaseSetGetClass is a PHP class that streamlines property handling in other classes. By extending this class, you can eliminate the need to manually create setters and getters for each property. Simply define a property, and the class will generate corresponding methods for setting and getting the property's value.

Usage

  • Extend BaseSetGetClass in your class definition:
class MyClass extends BaseSetGetClass {
    // Properties will automatically have setters and getters
    protected $name;
    protected $age;
}
  • Use the generated setters and getters:
$myInstance = MyClass::setName("Hichem")->setAge(22);

$name = $myInstance->getName(); // Returns "Hichem"

$age = $myInstance->getAge();

This class simplifies property manipulation, making your code more concise and maintainable. It eliminates the repetitive task of creating setters and getters for each property manually.

<?php
use BadMethodCallException;
class BaseSetGetClass
{
private static self $instance;
public static function __callStatic($method, $args) {
if (!isset(static::$instance) OR !static::$instance) {
static::$instance = new static();
}
return call_user_func_array([static::$instance, $method], $args);
}
public function __call(string $method, array $arguments)
{
if (method_exists(static::$instance, $method)) {
if (in_array($method, ["__setField", "__getField"])) {
throw new BadMethodCallException("Method $method does not exist.");
}
return call_user_func_array([$this, $method], $arguments);
} else {
if (str_starts_with($method, "set")) {
return static::$instance->__setField(strtolower(substr($method, 3)), $arguments[0]??null);
}
elseif (str_starts_with($method, "get")) {
return static::$instance->__getField(strtolower(substr($method, 3)));
}
throw new BadMethodCallException("Method $method does not exist.");
}
}
private function __setField(string $field, mixed $value): self
{
$this->$field = $value;
return $this;
}
private function __getField(string $field): mixed
{
return $this->$field;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment