Creating an object from a class in Codeigniter

前端 未结 2 1003
星月不相逢
星月不相逢 2021-02-03 16:10

The following codes are from http://d.hatena.ne.jp/dix3/20081002/1222899116 and codes are working well.

This is an example of using snoopy in codeigniter.

Q1. Am

相关标签:
2条回答
  • 2021-02-03 16:36

    Q1. You can use:

    $this->load->library('snoopy');
    

    In your controllers. And create a new instance like so:

    $snooper = new Snoopy();
    

    The reason they are using:

    if (!class_exists('Snoopy')) {
        require_once(APPPATH.'libraries/Snoopy'.EXT);
    }
    

    Is because you will get a fatal error if you try and use $this->load->library(), since the loader class is not available in the library. You can call it in a controller is because your controllers extend the controller class, which extends the ci_base class, which extends the ci_loader class which is where the functionality to make calls like $this->load comes from. The Scraping class that you've shown here does not. If you dig down you'll see that the loader is basically using include_once to include whatever class, helper etc. you're trying to use.

    Q2.

    $to_specialchars = true
    

    is being used in a couple the function declarations as parameters. Setting it '=true' is just setting a default, so you could can do this:

    echo $scrappy->getWebHtml('http://example.com');
    

    Which is identical to this:

    echo $scrappy->getWebHtml('http://example.com', true);
    

    If you look at the return statement of that function, you'll see they are $to_specialchars is being checked, and if it's true, then the output is run through the PHP function htmlspecialchars() first.

    Q3. If you look at the root of your codeigniter project, in index.php you'll see EXT defined as:

    define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
    

    and APPATH:

    if (is_dir($application_folder))
    {
    define('APPPATH', $application_folder.'/');
    }
    else
    {
        if ($application_folder == '')
        {
            $application_folder = 'application';
        }
        define('APPPATH', BASEPATH.$application_folder.'/');
    }
    

    So these are two constants being set at bootstrapping, so you can use them in your application, and if you were to ever change them, then it wouldn't instances like where you see it being used in the code you provided.

    Please next time have one question per stackoverflow question :)

    0 讨论(0)
  • 2021-02-03 16:46

    . This sample Scraping code was written based on using the library: "Snoopy - the PHP net client ( snoopy.sourceforge.net )"


    I tried to post it again. but I couldn't post with hyperlinks. sorry.. I'll answer to that in my site.(I'm a newbie stackoverflow.com :-( )

    I think that I'll try to repost these answers after a few days .

    ( http://d.hatena.ne.jp/dix3/20091004 )

    0 讨论(0)
提交回复
热议问题