Welcome Guest, Not a member yet? Register   Sign In
Extending UserAgent class
#1

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
Reply
#2

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?
Reply
#3

Read https://codeigniter.com/user_guide/exten...asses.html twice.
Creating your own class is not enough. See "Replacing Core Classes".
Reply
#4
Heart 

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

namespace App\Libraries;
use \CodeIgniter\HTTP\UserAgent as BaseUserAgent;

class MyUserAgent extends BaseUserAgent {
    // Your overriding methods here
}


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
public static function request(?App $config nullbool $getShared true)
{
    if ($getShared) {
        return static::getSharedInstance('request'$config);
    }

    $config $config ?? config('App');

    return new IncomingRequest(
        $config,
        AppServices::uri(),
        'php://input',
        new \App\Libraries\MyUserAgent() /// notice that this was modified to use your class
    );



Now, when you call $this->request->getUserAgent(), you'll receive an instance of your custom class.  Fuiyooooooh!
Reply
#5

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB