Extending UserAgent class |
Hello All,
I am porting our CI3 application to CI4 and am running into an issue with extending/overriding the UserAgent class in codeigniter to add additional methods for my application. per the documentation here: https://codeigniter.com/user_guide/exten...asses.html I created a UserAgent class and stuck it into app/Libraries <?php namespace App\Libraries; use CodeIgniter\HTTP\UserAgent; class UserAgent extends UserAgent { But find that codeigniter is not instantiating my instance when it creates a UserAgent object. In all honesty I'm not really sure how it could. Is there an additional step I'm missing in telling CI it should instantiate my UserAgent instead of its own? Thanks in advace! -Raymond
Haiyaa, why do you want to extend the useragent class?
That's a joke. What about adding an entry for your class file in /app/Config/Autoload.php?
Read https://codeigniter.com/user_guide/exten...asses.html twice.
Creating your own class is not enough. See "Replacing Core Classes".
Hello jacobs-kmi,
Here is what you need to do / can do. 1) Create a file in located at /app/Libraries/MyUserAgent.php with the following code: Code: <?php 2) Override the service(s) that call UserAgent, such that they use your class instead. To do this, open /app/Config/Services.php, and add this method, which was copied and modified from the system-level config: PHP Code: // This was copied from /vendor/codeigniter4/framework/system/Config/Services.php Now, when you call $this->request->getUserAgent(), you'll receive an instance of your custom class. Fuiyooooooh!
Thanks for the Help!
Bennycopter's solution worked; thankfully the Useragent class is only instantiated in one spot or it would require overriding/copying potentially a lot of core code. |
Welcome Guest, Not a member yet? Register Sign In |