What are some of the gotchas you’ve encountered with Silverstripe 4? What were your solutions?
With SilverStripe 4.1 and the new public
folder, the assets from mysite
and templates weren’t exposed during composer vendor-expose
. Turns out, you have to change your project to be of type "silverstripe-recipe"
in composer.json. Eg. "type": "silverstripe-recipe"
One of the most prevalent issues, especially for people moving from SS3 seems to be namespacing. If you’re getting method 'blah' does not exist on 'blah'
error messages, then it’s quite often a namespacing issue.
It’s a bit old, but there’s a nice little summary of how PHP namespaces work here:
PHP Namespaces in under 5 Minutes > PHP Namespaces in Under 5 Minutes | SymfonyCasts
Apply those principles to SS4
Namespaces and template structure
Owns and publishing of files / images
This is a really common one. It can be solved using the owns
api on versioned dataobjects, but we don’t yet have access to that for non-versioned objects (such as SiteConfig, for example). We’ll be able to use owns
on non-versioned dataobjects in 4.1 so that will help a lot, but until then the solution is to use publish single in onBeforeWrite (or onAfterWrite).
public function onBeforeWrite()
{
if($this->Image() && $this->Image()->exists()) {
$this->Image()->publishSingle();
}
parent::onBeforeWrite();
}
@zanderwar wrote some code that will do this generically by looping the has_one relations:
public function onBeforeWrite()
{
parent::onBeforeWrite();
/** @var Image $relation **/
foreach (static::$has_one as $key => $relation) {
if ($relation == Image::class && !$this->{$key}()->exists() && !$this->{$key}()->isPublished()) {
$this->{$key}()->publishSingle();
}
}
}