Search code examples
phpenumsnamespaceslaravel-5psr-4

Using Enum classes in Laravel 5 project


I want to use some enum classes in my laravel 5 app. They are modeled after this PHP man page example: http://php.net/manual/en/class.splenum.php

The file app\Enums.php looks like this:

<?php
namespace MyApp\Enums;
class ItemStates extends SplEnum 
{
    const __default = self::Active;

    const Active = 1;
    const Pending = 2;
}

class ItemVisibility extends SplEnum
{
    const __default = self::Community;

    const Community = 1;
    const Personal = 2;
}

I want to use these from a controller. I put a use statement at the top of my controller:

use MyApp\Enums;

When I try to use the class like this:

if ($category['Family'] == CategoryFamily::General)

I get an error: Class 'MyApp\Http\Controllers\Quiz\CategoryFamily' not found

I have run compose dump-autoload in case that matters.

How can I use my Enum classes from inside controllers (multiple controllers)?


Solution

  • Please correct me if I'm wrong, but Laravel uses a PSR-4 compliant autoloader. In the documentation of psr-4 it is mentioned:

    The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

    You can check if it uses this standard in your composer.json file to be sure:

    "psr-4": {
        "MyApp\\": "app/"
    }
    

    This means it won't be able to find your class. I suggest you put each class into a separate file with the same name as the class and put that in a MyApp\Enum namespace for example.

    The other options you have are to include your app using the psr-0 standard in your composer.json, or to manually include your Enum file wherever you want it.

    UPDATE

    Once you've done this, you should be able to use SplEnum by putting use SplEnum; under the namespace .. in top of your file, if and only when you have SplTypes installed. If you're on Windows or do not want to install this PECL Extension, then I suggest this answer: https://stackoverflow.com/a/254543/2433843 with an elegant solution.