Sitemap
Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

How to override default behavior in the Statamic CMS

4 min readNov 27, 2023

--

Expert Guide to Customizing Statamic CMS: Overriding Default Settings with Composer

Press enter or click to view image in full size
Overriding Statamic Behavior

Hey there fellow developers! Let’s talk about customizing your CMS — it’s not always plan A, but sometimes it’s the only plan that works. You know how it is: tight deadlines, unique project needs, or just a lack of alternatives. There are times when the only way forward is to roll up your sleeves and dive into overriding the default behavior of your CMS.

I’ve been there myself. In one of our projects, we needed a smoother way to generate live preview tokens in Statamic CMS to ease front-end integration. Though we eventually took a different route by tweaking the client application, my time spent using the override setup was nothing short of a revelation — it worked like a charm!

If you’re facing a similar challenge, I’m here to share my adventure. Maybe my story can shed some light on your path and save you some headaches. 👍

Here’s what we’ll cover:

  1. Picking the right files to override — choose wisely!
  2. Setting up your own ‘overrides’ directory and getting into autoload.
  3. Copying those files and mirroring their namespaces
  4. Giving those copied files your personal touch.
  5. Running ‘dump-autoload’ and keeping your CI in the loop.

Ready to make some CMS magic happen? Let’s get started!

Files to override

Deep dive into the vendor directory and choose files which is responsible for the behavior you would like to update. In my case, it was only one file:

vendor/statamic/cms/src/CP/LivePreview.php

Create the “overrides” directory

Create a directory in your project’s root where you want to save override files. In my case, I created a folder called “overrides”, simple! 😄 Then add the directory for a specific namespace, like “statamic”.

Now we need to autoload our directory under the needed namespace using composer. Find the “autoload” key in your composer.json file and add “Statamic\\” namespace:

"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/",
"Statamic\\": "overrides/statamic"
}
},

It means that everything in your overrides/statamic folder will be autoloaded by the composer using PSR-4 standard and set under Statamic\ namespace

Replicate the directory system to match PSR-4 and copy files

Now, you need to replicate the namespace of your files as folders to match psr-4. In my case, the namespace of my LivePreview.php is Statamic\CP:

<?php

namespace Statamic\CP;

use Illuminate\Support\Facades\Cache;
use Statamic\Contracts\Tokens\Token as TokenContract;
use Statamic\Facades\Token;
use Statamic\Tokens\Handlers\LivePreview as Handler;

class LivePreview
{
public function tokenize($token, $item): TokenContract
{
$token = tap(Token::make($token, Handler::class))->save();

Cache::put('statamic.live-preview.'.$token->token(), $item, now()->addHour());

return $token;
}

public function item(TokenContract $token)
{
return Cache::get('statamic.live-preview.'.$token->token());
}
}

While I already have Statamic\ namespace set by the composer, I only need to add a directory named “CP” and copy the LivePreview.php file there.

Get Revaz Gh. (MaestroError)’s stories in your inbox

Join Medium for free to get updates from this writer.

File from vendor:

vendor/statamic/cms/src/CP/LivePreview.php

Is overridden by:

overrides/statamic/CP/LivePreview.php

You need to make this for every file you need to override. Till now, the LivePreview.php file remains with the same content.

Update files

We can start to update file(s). I was trying to make as small changes as possible to keep native logic untouched.

  • Updated $token variable to be set by config (.env)
  • Added the getCacheKeyWithUser method to ensure preview data will be still different for each user.
  • Updated item method to get correct data from cache
  • Made static preview token controllable from configuration (.env)
<?php

namespace Statamic\CP;

use Illuminate\Support\Facades\Cache;
use Statamic\Contracts\Tokens\Token as TokenContract;
use Statamic\Facades\Token;
use Statamic\Tokens\Handlers\LivePreview as Handler;
use Illuminate\Support\Facades\Auth;

class LivePreview
{
public function tokenize($token, $item): TokenContract
{
if (config("app.statamic_preview_static_token_enabled")) {
$token = config("app.statamic_preview_static_token");
}
$token = tap(Token::make($token, Handler::class))->save();

$cacheKey = $this->getCacheKeyWithUser($token);

Cache::put($cacheKey, $item, now()->addHour());

return $token;
}

public function item(TokenContract $token)
{
$cacheKey = $this->getCacheKeyWithUser($token);

return Cache::get($cacheKey);
}

public function getCacheKeyWithUser(TokenContract $token) {
$userId = Auth::user()->id;

$cacheKey = 'statamic.live-preview.';
$cacheKey .= $userId . ".";
$cacheKey .= $token->token();
return $cacheKey;
}
}

Note: This file is part of your project as any other and it is shipped with your repository. So, you can freely use any Laravel or third-party package features here.

Run dump-autoload

To test your updates, you need to run a command once:

composer dump-autoload

It will update your autoload file and an override will happen! 🚀 Just don’t forget to add this command in your CI/CD pipeline if it isn’t already there 👍

Resources

P.S. This article is free from affiliate links and sponsored content. All information and opinions expressed are solely the result of my personal insights.

Let's Network! 🤝
Connect with me on LinkedIn for more insights and discussions.
-----
Enjoyed the Read? 📖
Hit the 'Follow' button on my Medium profile for more cutting-edge content.

--

--