In my application, I have several types of post:
Archives, videos, photos, draft, etc.
I use in several places an array like :
$type = ['draft'=>'Draft post',"photo"=>'Photo posts','live'=>'Live','archive'=>'Archive']
This can be in views to create a select, or in my controllers or model to display the different types or make validations.
I don’t want to add a types table in my database.
What is the best way to define this array once in my application and not have to copy it several times?
This could allow me to add a post type by modifying this array in one place in my app.
You could create a public static property in your application like this
class Application extends BaseApplication
public static array $postTypes = ['draft', 'photo', 'live'];
and reference them in your Application class like
$types = self::$postTypes;
or in any other PHP class like this
$types = \App\Application::$postTypes;
This is just basic PHP class functionality, nothing really cakephp specific so you could also just create your own custom class inside your
src folder and use it as a source for all your Post types.
I’d recommend you watch my video about re-using code from 2021 cakefest.
I wasn’t sure where to put this, thanks!
PostsTable::$postTypes would be a more appropriate location for the property than the
An even better alternative would to use an enum class of the types. Cake 5 will also have mapping of enum classes to table columns which would make using the enum class even more seamless.
Like Admad suggested, I would recommend using enums too. Example below, you will be able to get the
String from it. eg :`
* Storage classes available in S3
enum AwsS3StorageClasses: string
case STANDARD = 'STANDARD';
case REDUCED_REDUNDANCY = 'REDUCED_REDUNDANCY';
case STANDARD_IA = 'STANDARD_IA';
case ONEZONE_IA = 'ONEZONE_IA';
Thats only possible if you are on PHP 8.1+
But of course if you are on that version then an enum is the best way to represent that.