Spacha / PoliisiautoServer

A server for an application where users can report bullying to a trusted adult.
BSD 2-Clause "Simplified" License
2 stars 1 forks source link

Back-end scaffolding #2

Closed Spacha closed 1 year ago

Spacha commented 1 year ago
Spacha commented 1 year ago

https://tighten.com/blog/extending-models-in-eloquent/

Spacha commented 1 year ago

For user roles, we could possibly do something like this:

<?php

class Model {
    public function __construct(array $attributes = []) {}
}

class Role
{
    const ROLE_LIMITS = [0, 3];

    const STUDENT       = 1;
    const TEACHER       = 2;
    const ADMINISTRATOR = 3;

    const HUMAN_READABLE = [
        self::STUDENT       => "student",
        self::TEACHER       => "teacher",
        self::ADMINISTRATOR => "administrator"
    ];

    public static function forHumans(int $role) : string
    {
        if ( !($role >= 0 && $role <= 3) )
            throw new UnexpectedValueException("Role between {self::ROLE_LIMITS[0]} and {self::ROLE_LIMITS[1]} expected, got $role!");

        return self::HUMAN_READABLE[$role];
    }
}

abstract class User extends Model
{
    public $role;

    final public function __construct(array $attributes = [])
    {
        // Force definition of ROLE constant in each child
        $this->role = static::ROLE;
    }

    /**
     * Adds a global scope to always refer to a certain type
     * of user (Student, Teacher, Administrator).
     */
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope(function ($query) {
            $query->where('role', $this->role);
        });
    }
}

class Teacher extends User
{
    const ROLE = Role::TEACHER;

    protected $table = 'users';

    public function organisation()
    {
        return 'Vihannin Koulu';
    }
}

class Student extends User
{
    const ROLE = Role::STUDENT;

    protected $table = 'users';

    public function organisation()
    {
        return 'Vihannin Koulu';
    }
}

$ope = new Teacher();
var_dump( $ope->role );
var_dump( Role::forHumans($ope->role) );

$oppilas = new Student();
var_dump( $oppilas->role );
var_dump( Role::forHumans($oppilas->role) );