Not understanding how to use external php library

I have a project I need to use with QueryPath ( https://github.com/technosophos/querypath ).

I created a new YII2 installation with a basic template and installed QueryPath with Composer.

The problem I am having is that I can’t figure out how to correctly call QueryPath…

I created a controller and view and I am calling them correctly because I working test code.

Here is my controller…





<?php


namespace app\controllers;


use Yii;

use yii\web\Controller;


class ImportController extends Controller

{




    public function actionImport()

    {


		$title1 = QueryPath::withHTML('<html><head></head><body><h1>this is title1</h1><h2>this is title2</h2></body></html>', 'h1')->text();


		$title2 = QueryPath::withHTML('<html><head></head><body><h1>this is title1</h1><h2>this is title2</h2></body></html>', 'h2')->text();    


//		$title1 = "title1";

//		$title2 = "title2";		

		

		return $this->render('index', [

			'title1' => $title1,

			'title2' => $title2,

		]);





	}


}






I expect that I need to include a ‘use’ statement at the top, but I have not been able to figure out what to put in it. The class autoloader is a black box that does magic stuff to me.

QueryPath.php installed to vendor\querypath\querypath\src\QueryPath.php

Thanks for any help!!

-John

The problem is not related to Yii, Composer or class autoloading, it’s basic PHP syntax.

You have a namespace declaration at the beginning of the file:




namespace app\controllers;



It means that your code




$title1 =  QueryPath::withHTML('<html><head></head><body><h1>this  is title1</h1><h2>this is  title2</h2></body></html>', 'h1')->text();



refers to class \app\controllers\QueryPath which doesn’t exist. (PHP namespaces)

You have to either use the fully qualified name:




$title1 = \QueryPath::withHTML('<html><head></head><body><h1>this  is title1</h1><h2>this is  title2</h2></body></html>', 'h1')->text();



or add an use statement:




use QueryPath;

// ...

$title1 = QueryPath::withHTML('<html><head></head><body><h1>this  is title1</h1><h2>this is  title2</h2></body></html>', 'h1')->text();



Thank you phtamas!

I figured it was something kind of simple and that I was just missing it.

I am still in the early stages of using YII and it is really pushing my knowledge of PHP! ;D

I really like having the forum available to help point out which way to look.

Thanks again!

-John