zvaehn
January 5, 2018, 4:40pm
1
Hello,
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?
zvaehn
January 5, 2018, 6:03pm
3
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.
zvaehn
January 5, 2018, 6:11pm
5
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
asset::$methods['someMetho...
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
zvaehn
January 8, 2018, 5:14pm
7
Seems to be the best alternative so far. Thank you.
Where is the best way to place and load the class?
zvaehn
January 8, 2018, 5:20pm
9
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.
zvaehn
January 8, 2018, 5:42pm
11
plugins/background-image/background-image.php:
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
EDIT:
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.