Is my library function from common file a good practice ? |
I created this library function in app/Common.php because i want to call easier my libraries but i don't know if this function is a good practice for codeigniter 4. Please tell me if this function is a good practice.
app/Common.php PHP Code: if ( !function_exists('library') ) { app/Controllers/Home.php PHP Code: <?php namespace App\Controllers; app/Libraries/ShopLibrary.php PHP Code: <?php namespace App\Libraries;
No, it is not.
1. You are making your own unique loading system that somebody else should get used with. Also, this system makes your code less portable. 2. Your function always returns a new instance. Is this always needed? Sometimes singletons are more appropriate. 3. In your sample usage code how do you decide when to use static or dynamic methods? It looks messy. Edit: You don't need one "good practice", you need a "bag of tricks", a repertoire on how to create objects and on how to access them easily. Object creation depends on the context, and on object's purpose. There are known patterns for these things, get familiar with these concepts when you have the time. While your project is not too demanding try to stick with what CodeIgniter has got now: https://www.youtube.com/watch?v=iqQufhllUCo If things get complicated too much and what CodeIgniter proposes is not enough, maybe then you would adopt a more complicated solution that would require more experience. But don't try to invent one. See for example https://php-di.org/ , https://github.com/PHP-DI/PHP-DI
(06-30-2020, 04:13 PM)ivantcholakov Wrote: No, it is not. Thank you so mouch @ivantcholakov Here i set public for priceFormat just for call library with static and public method I'm beginner in ci4 and i want learn this framework because i like so much. With some days a go i started documentations about this codeigniter 4 and i have tons of questions... I want use this ShopLibrary in all controllers. Which is the best solution ? If you know other solution for "autoload" library please put here. app/Config/Services.php PHP Code: <?php namespace Config; app/Controllers/BaseController.php PHP Code: <?php app/Controllers/Home.php PHP Code: <?php namespace App\Controllers;
Try this
Code: $this->shopLibrary = \Config\Services::shopLibrary(); This way you will have a singleton. And since you have an instance, avoid using static methods, because they will force you to remember and recall what is the full namespace of the library, which is not convenient. And we all know it is a library, maybe just "shop" would be nicer than "shopLibrary". Edit: Or "shopping" if you want to avoid a future name collision.
|
Welcome Guest, Not a member yet? Register Sign In |