Extending Kirby objects (Assets)


i wonder if there is a possibility to extend the asset-object like it is possible with files as described here: https://getkirby.com/docs/developer-guide/objects

I tried to create a file from my asset like so:

new File($image);

// https://forum.getkirby.com/t/file-object-from-file-in-assets/3720
new Media($image); 

…but this does not seem to work.
Thank you!

The media class requires two parameters, the path and the URL.

What exactly are you trying to do?

I want to generate a safename and use it as a classname for background-images.
$file->safeName() is not enough in some cases.

You could extend the Asset class and create some new methods, I think.

Yeah, thats exactly what i am trying to do.

file::$methods['getSaveCSSSelector'] = function($file) {
  return getSaveCSSSelector($file); // returns the safe name.

works for files, but not for assets.
I get an exception when i try to


No, that is not possible, what I meant is create a new Class

class MyAsset extends Asset {
  // overwrite the safeName method
  public function safeName() {
   return 'xyz';
  // or create a new method
  public function getSafeCssSelector() {
  // return whatever

Then create a MyAsset object and work it from there

$asset = new MyAsset('assets/images/someimage.jpg');
echo $asset->safeName(); // -> xyz

Seems to be the best alternative so far. Thank you.
Where is the best way to place and load the class?

Put it in a plugin file.

That is what i was trying to do, but it seems that the Asset-Class cannot be found. Do i have to define a namespace where Asset is located?

That is strange, works for me. I put the code into a new file myasset.php in /site/plugins.


class BackgroundImage extends Asset {
  public function safeName() {
    $safeName = parent::safeName();
    $safeName = preg_replace('/[^a-zA-Z0-9_-]+/', "_", $safeName);
    return "s-" . $safeName;

In another plugin, i require the class and call:

$asset = new BackgroundImage($image->root());
$safeName = $asset->safeName();

and i get:

Fatal error: Class ‘Asset’ not found in […]site/plugins/background-image/background-image.php on line 3

Seems to work just fine, when i require the class just before calling

new BackgroundImage($image->root());

Hm, a bit strange that the Asset class is not found. If you define a new class in a plugin, it is auto-loaded (so you can use it in templates and controllers). In another plugin, it depends on the loading order of the plugins.