I’m trying to cleanup my code a bit (I had an awful lot of business logic in the view template…) but I’m currently struggling a bit.
You see, I want to add a prefix to all titles on my blog based on it’s publication status.
to do this, I have written the following code ($articles is actually a QueryBuilder ResultSet turned into an array):
$articles = ...->toArray();
foreach($articles as $key => $article) {
// Check if we need to add a prefix to the title
switch($article->published) {
case 0:
$articles[$key]->title = "Private: " . $article->title;
break;
case 2:
$articles[$key]->title = "Unlisted: " . $article->title;
break;
}
}
However, I wondered if there is a way to do this more cleanly…
Mostly because I don’t want to turn it into an array, just for this (as I’ll have to paginate it later down the road).
You need the result query to be something similar to this:
SELECT Article.id, … ,
CASE
WHEN Article.published=0 THEN CONCAT("Private: ", Article.title)
WHEN Article.published=2 THEN CONCAT("Unlisted: ", Article.title)
END AS Article__titlewithstatus
FROM articles AS Article
WHERE …
Taking the CASE-way of doing this, how much more efficient is this in compared to the for-loop I’m using right now?
Is there a different way of achieving this for if I need to do other stuff with the results later?
Because I still need to modify the body field of the table later down the road as well to strip HTML tags n such.
But now I need to add the CASE but I don’t know where (and how) to add the case (this current code only is able to add the private prefix but not the unlisted one…
I’ll have to give it a try when back at the office tomorrow.
What I could do is make an entity in the app that extends the entity of the plugin right?
Would there be any other way to do it cleanly or is this the way I should go?
Oh whoops… I thought I did mention it… my apologies…
Well… I do control the plugin but considering what I’m trying to do is fairly “specific” to the app I’m making (eg. my team doesn’t want this in the plugin itself - yet), just assume that I don’t have control over the plugin.
I haven’t tried to do something like that. You might need to make your own table and entity classes, extending the plugin ones? That seems like a lot of work, and things to maintain, just to add such a tiny bit of functionality. Given all that, I’d probably go with an element instead.
It’s not quite as DRY as an accessor would be, but better than repeating the if/else everywhere, and maybe better than adding the case stuff into all your related queries?
Sometimes, doing it in the view really is the right way. You can’t possibly remove all business logic from your views. But it’s worth thinking through scenarios before you decide to do it. If not for the plugin architecture here, an accessor would probably be the way to go.