Use a custom function everywhere in the website

2019-07-31 23:30发布

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条回答
放我归山
2楼-- · 2019-08-01 00:07

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.

查看更多
登录 后发表回答