Use elasticsearch in symfony2 - php

I have installed elasticsearch using composer. This is my AppKernel.php file
new Elasticsearch\Client()
This is my TestController.php file.
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Elasticsearch\Client;
//use Elasticsearch\Common\AbstractFactory;
class TestController extends Controller{
/**
* #Route("/", name="test-homepage")
*/
public function indexAction(){
$client = new Elasticsearch\Client();
dump($client);
die;
}
}
I am using eclipse as my ide and it shows me error like elasticsearch\Client cannot be resolved.Why is this not working?

First of all: If you define use statement then you don't need FQCN. BTW your FQCN is not right it should starts with \ to prevent loading class from current namespace.
Then: in AppKernel.php you need to define bundles, not every library you installed.
If you have small experience in PHP try to use more easy-to-study frameworks. Symfony is mostly for experienced developers.
If you think that you can work with Symfony then I would recommend you bundle for integrating ElasticSearch and Elastica: https://github.com/FriendsOfSymfony/FOSElasticaBundle. It will save your time.

You should try to instanciate the imported class, using the short name (base on the use statements on your class), like this :
$client = new Client();
Or with the FQCN :
$client = new \Elasticsearch\Client();
(note that the new statement begin with a \ which prevent from trying to load the class from the current namespace (ie : AppBundle\Controller : \AppBundle\Controller\Elasticsearch\Client)

Related

Symfony 2 - non bundle library integration and location

I am all about the best practice of symfony 2 and I would like to integrate a php library into the project. Library is a non bundle, a simple php class with some methods.
My question just follows the following, which DOES NOT have an accepted answer. Anyway from what I read here I decided to autoload the class, but have no idea where should I locate the php file.
Maybe src/MyBundle/DependencyInjection/? I really doubt it since library has no dependency of other services I have.
Should I create a directory like src/MyBundle/Services/ or src/MyBundle/Libraries/?
What is the best practice here?
as mentioned by b.enoit.be create a service from the class.
MyBundle/Service/MyServiceClass.php
<?php
namespace MyBundle\Service;
class MyService
{
...
}
app/config/services.yml
services:
app.my_service:
class: MyBundle\Service\MyService
use it e.g. in a controller
MyBundle/Controller/DefaultController.php
<?php
namespace MyBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
...
// get the service from the container
$yourService = $this->get('app.my_service');
...
}
}
?>

PHP Symfony error: "did you forget to use a use statement", regardless of class/function

I have started building a new Web App using Symfony, but am having issues using classes.
PhpStorm is able to find the functions within the classes (due to the fact that it gives suggestions when you type $className->.
Also, to prove this is not the same as the other similar questions, I have over simplified it, and even so, the error still occurs.
I have the below in my DefaultController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use testBundle;
use AppBundle\domainionClasses\firstlevelchecks;
class DefaultController extends Controller
{
/**
* #Route("/register",name="register")
*/
public function registerAction(){
$testClass = new firstlevelchecks();
$testing = $testClass->donothing(); //the IDE knows that the function donothing() exists, in fact it suggests it.
return new Response('');
}
}
The below is the php class located in AppBundle/domainionClasses/test1.php
<?php
namespace AppBundle\domainionClasses;
class firstlevelchecks
{
function donothing(){
return null;
}
}
When loading the /register route, the below Symfony error is displayed:
Attempted to load class "firstlevelchecks" from namespace "AppBundle\domainionClasses".
Did you forget a "use" statement for another namespace?
It is attempting to load the class from the correct name space, and I have used a use statement.
Is there anything I am missing here, or is there a problem with Symfony? This is the first time I used the new version of PhpStorm, and have just downloaded the plugin, also the first time I have experienced this issue :(
Because your file is named test1.php, how can the autoloader know which file to include ?
You shoud rename it to firstlevelchecks.php (= the name and case of your class).

Symfony2.7, adding 3rd party lib to project

I'm stuck, i wanted to load external library to my symfony2 project but got error stating that class was not found my app/autoloader.php:
...
$loader->add('Tinify', __DIR__.'/../vendor/tinify/tinify/lib');
...
and my file where i want to use it looks like it:
<?php
namespace XYZ\NewsBundle\Controller;
...
use Tinify;
class NewsController extends Controller{
...
public function displayAction($slug)
{
$em = $this->getDoctrine()->getManager();
$external = new \Tinify();
}
error is as follow The autoloader expected class "Tinify" to be defined in file "xyz/app/../vendor/tinify/tinify/lib\Tinify.php". The file was found but the class was not in it, the class name or namespace probably has a typo.
but file under vendor\tinify\tinify\lib\Tinify.php
namespace Tinify;
const VERSION = "1.3.0";
class Tinify {
...
}
i checked if it really has typo but don't see one
Full qualified class name of Tinify is not Tinify but \Tinify\Tinify. Its namespace + classname.
In you NewsController class you should do:
use \Tinify\Tinify;
Also note the backslash at the beginning of the namespace.
Then in the code you should use just class name and not namespace so also change this:
$external = new \Tinify();
to this:
$external = new Tinify();
Why don't install Tinyfy throught Composer?
composer require tinify/tinify
In this way composer handles de autoload of the library, you don't need to load manually nothing, you only must to make an instance of the class and run
$tinify = new Tinify();

Cannot debug service even if it is registered in the container

I use the following to learn about services and their definition:
<?php
namespace Members\Bundle\ManagementBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class IndexController extends Controller
{
public function learnAction()
{
$container= new ContainerBuilder();
$container->register('test_service','User');
var_dump($container->hasDefinition('test_service')); // return true
return new Response("hi");
}
}
The service test_service is registered and the var_dump echoes true. But when I come back to console and try to debug using:
php app/console container:debug test_service
[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
The service definition "test_service" does not exist.
container:debug [--show-private] [--tag="..."] [--tags]
[--parameter="..."] [--p arameters] [name]
What am I not understanding well? Your usual help is much appreciated.
You should define your services in one of the configuration files loaded by Symfony when building your container.
In your example you're manually instantiating a container builder, but this is not the builder used by Symfony when defining its container.
If you define your service in for example app/config/services.yml it will be available for the console command.

Using namespaces in Laravel 4

I'm new to Laravel and using PHP namespaces in general. I didn't run into any problems until I decided to make a model named File. How would I go about namespacing correctly so I can use my File model class?
The files are app/controllers/FilesController.php and app/models/File.php. I am trying to make a new File in FilesController.php.
Namespacing is pretty easy once you get that hang of it.
Take the following example:
app/models/File.php
namespace App\Models;
class File {
public function someMethodThatGetsFiles()
{
}
}
app/controllers/FileController.php
namespace App\Controllers;
use App\Models\File;
class FileController {
public function someMethod()
{
$file = new File();
}
}
Declare the Namespace:
namespace App\Controllers;
Remember, once you've put a class in a Namespace to access any of PHP's built in classes you need to call them from the Root Namespace. e.g: $stdClass = new stdClass(); will become $stdClass = new \stdClass(); (see the \)
"Import" other Namespaces:
use App\Models\File;
This Allows you to then use the File class without the Namespace prefix.
Alternatively you can just call:
$file = new App\Models\File();
But it's best practice to put it at the top in a use statement as you can then see all the file's dependencies without having to scan the code.
Once that's done you need to them run composer dump-autoload to update Composer's autoload function to take into account your newly added Classes.
Remember, if you want to access the FileController via a URL then you'll need to define a route and specify the full namespace like so:
Route::get('file', 'App\\Controllers\\FileController#someMethod');
Which will direct all GET /file requests to the controller's someMethod()
Take a look at the PHP documentation on Namespaces and Nettut's is always a good resource with this article
first, load your class with:
$ composer dump-autoload
then
$file = new File;
// your stuff like:
$file->name = 'thename';
$file->active = true;
$file->save();
Section: Insert, Update, Delete on Laravel 4 Eloquent's doc
To namespace your model, at the top of your model class right after the opening
Then when you call from controllers you will call new Whatever\Model;
You probably have to do a dump-autoload with composer the first time around.
have a look to it.. hopefully will clear your query....
<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\users;
class UserController extends Controller{
public function actionIndex()
{
echo "working on .....";
}
}
Namespaces are defined at the top of PHP classes right after the opening php script tag like this:
<?php
namespace MyNameSpace;
When you then want to use the namespaced class in some other class, you define it like this:
new MyNameSpace\PhpClass;
or import it at the top of the file (after namespaces if present) like this:
<?php
//namespace
use MyNameSpace\MyPHPClass;
//then later on the code you can instantiate the class normally
$myphpclass = new MyPHPClass();
In Laravel namespaces can be defined anywhere composer can autoload them, I'd recommend defining namespaces within the app directory. So you can define a namespace like Utils for holding Utility classes by creating a Utils directory in the app directory, creating our utility classes and defining the namespace as we did above.
Afterwards you have run the command to ask composer to autoload classes:
$ composer dump-autoload

Categories