Use a custom function everywhere in the website

守給你的承諾、 提交于 2020-01-05 15:15:26

问题


I come from the procedural PHP and am learning OOP with Laravel. What I learned so far is very interesting and will ease my developer's life (it's not my job btw). So, for all my websites, I am using a slug property for all articles, categories, and so on. I started to use the "str_slug" provided by Laravel which seems to do the job at 99%. The issue I get is when I have such title (in french): "J'ai mangé une pomme", the slug string I get is: "jai-mange-une-pomme" which, in french, is not correct. I would like "j-ai-mange-une-pomme".

It's not really an issue. I can do:

$slug = str_replace('\'','_',$input['name']);
$slug = str_slug($slug, '-');

It suits me well but I wonder how to use anytime I want to use it. I don't want to write it again and again and again. In procedural, it's easy, I would write a function, such as thePerfectSlug(){} in a helpers.php file (still an example) and will use an include at the top of my index.php. That would do the job.

But in OOP and especially in Laravel (5.1), how can I do that?

Thanks


回答1:


You still can achieve it with normal function. Laravel uses his own function which are stored in helpers.php file. You can make your own helpers.php file and add it to your main composer.json file at autoload.files.

If you would like to do it in OOP way, create a trait like App\Traits\Sluggify with your method and use it in any class that needs it.



来源:https://stackoverflow.com/questions/33058779/use-a-custom-function-everywhere-in-the-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!