gregoriohc/byname

PHP trait for bynaming (nicknaming) classes/objects

v1.0.2 2021-06-08 19:00 UTC

This package is auto-updated.

Last update: 2022-06-08 21:17:16 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

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.