Skip to content

Instantly share code, notes, and snippets.

@lekoala
Last active February 9, 2024 08:17
Show Gist options
  • Save lekoala/5e7358138181ddcdf0533d8f4fdb70d0 to your computer and use it in GitHub Desktop.
Save lekoala/5e7358138181ddcdf0533d8f4fdb70d0 to your computer and use it in GitHub Desktop.
Using Attributes for SilverStripe routing
<?php
trait ImprovedController
{
/**
* Override default mechanisms for ease of use
*
* @link https://docs.silverstripe.org/en/5/developer_guides/controllers/access_control/
* @param string $action
* @return boolean
*/
public function checkAccessAction($action)
{
// Check if we have our attribute
if (method_exists($this, $action)) {
$refl = new ReflectionMethod($this, $action);
// Fetch all action attributes, if we have any, it's valid
$attributes = $refl->getAttributes(IsAction::class, \ReflectionAttribute::IS_INSTANCEOF);
if (!empty($attributes)) {
return true;
}
}
return parent::checkAccessAction($action);
}
}
<?php
#[\Attribute]
class IsAction
{
}
<?php
class MyController extends Controller {
#[\IsAction]
public function dosomething(HTTPRequest $req)
{
// do something
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment