Last active
February 9, 2024 08:17
-
-
Save lekoala/5e7358138181ddcdf0533d8f4fdb70d0 to your computer and use it in GitHub Desktop.
Using Attributes for SilverStripe routing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
#[\Attribute] | |
class IsAction | |
{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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