gregoriohc / byname
PHP trait for bynaming (nicknaming) classes/objects
Requires
- php: ~5.6|~7.0|~8.0
- gregoriohc/static-cache: ^1.0
Requires (Dev)
- phpunit/phpunit: >=4.0
- squizlabs/php_codesniffer: ^2.3
This package is auto-updated.
Last update: 2024-12-09 03:21:26 UTC
README
PHP trait for bynaming (nicknaming) classes/objects.
Install
Via Composer
$ composer require gregoriohc/byname
Usage
By default, the class byname is the class basename (without namespace).
class MyClass { use HasByname; } echo MyClass::byname(); // MyClass
Removing prefix and/or suffix
You can remove some characters from the beginning (prefix) or the end (suffix) of the byname overriding the bynamePrefix
and bynameSuffix
methods and returning the string to remove or the number of characters.
class MyClass { use HasByname; protected static function bynamePrefix() { return 'My'; } } echo MyClass::byname(); // Class
class MyClass { use HasByname; protected static function bynameSuffix() { return 5; } } echo MyClass::byname(); // My
A more complex example, mixing this with inheritance:
abstract class BaseController { use HasByname; protected static function bynameSuffix() { return 'Controller'; } public function model() { $class = '\\App\\' . $this->byname(); return new $class(); } } class UserController extends BaseController { ... } echo UserController::byname(); // User $user = (new UserController)->model(); print_r($user); // App\User Object (...)
Custom byname
You can set a custom byname overriding the bynameValue
method.
class MyClass { use HasByname; protected static function bynameValue() { return 'Cool'; } } echo MyClass::byname(); // Cool
Case
Yu can also get the name in three diferent cases:
class MyClass { use HasByname; } echo MyClass::bynameSnake(); // my_class echo MyClass::bynameCamel(); // myClass echo MyClass::bynameStudly(); // MyClass
Testing
$ composer test
Change log
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email gregoriohc@gmail.com instead of using the issue tracker.
Socialware
You're free to use this package, but if it makes it to your production environment I highly appreciate you sharing it on any social network.
Credits
License
The MIT License (MIT). Please see License File for more information.