Creating an object from a class in Codeigniter

喜夏-厌秋 提交于 2019-12-02 21:28:50

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 :)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!