Monday 24 October 2016

function - PHP Laravel use helper class in all views

I would like to create a helper (function) to avoid repeating code between all views in Laravel 5. The function should be using data from the database (Eloquent), so it cannot be just a simple function or a generic view composer.



Ideally it should be something like:




{!! Helper::addLinks($text) !!}


Where the Helper class uses Eloquent to validate the $value. I would like to avoid changing all Controllers. What is the best practice for this?



Update; I have the following working prototype. This function searches the text and replaces words found from the dictionary with hyperlinks:



function addLinks($text) {
//retrieve words from database

$words = Words::all();

//build dictionary with values that needs replacement
$patterns = array();
foreach ($words as $word) {
$patterns[$word->id] = $word->word_name;
}

//build dictionary with values the replacements
$replacements = array();

foreach ($words as $word) {
$replacements[$word->id] = "id . "\">" . $patterns[$word->id] . "";
}

//return text, replace words from dictionary with hyperlinks
return str_replace($patterns, $replacements, $text);
}


I want to use this function in several text blocks and paragraphs in the views. What approach is best?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...