Laravel 4 PHP: 'Use' statement with both local files and package files - php

I am trying to include a custom defined validation file that is local to my system and wish to use it with 'package' files from an application I downloaded online. The purpose is so that I can have my own custom validators since I made modifications to this application.
I keep getting the error -> 'Class 'Models\Validators\Photo' not found'
Controller:
use JeroenG\LaravelPhotoGallery\Controllers\AlbumsController; /* From Package */
use JeroenG\LaravelPhotoGallery\Controllers\PhotosController; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Album; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Photo; /* From Package */
use Models\Validators as Validators; /* Custom local file */
class EditPhotosController extends PhotosController {
public function __construct()
{
parent::__construct();
}
public function update($albumId, $photoId)
{
$input = \Input::except('_method');
$validation = new Validators\Photo($input); // Here's where error occurs
/* Validation check and update code etc. */
}
}
}
Photo.php -> File path: Models\Validators\Photo.php
namespace Models\Validators;
class Photo extends Validator {
public static $rules = array(
'album_id' => 'required',
'photo_name' => 'required',
'photo_description' => 'max:255',
);
}
Is this just a simple namespacing issue?

The most likely problem is that composer doesn't add file Models/Validators/Photo.php to the autoload index. Make sure you have provided correct path for your files in composer.json.

Try running
composer dump-autoload
to regenerate the autoload files.

Related

Elastic search configurations not working in laravel v5.3

I have setup new laravel v5.3 project and install elastic search driver to implement elastic search via composer. But when I reload my page then I always receive This page isn’t working even the elastic search is running on my system below is my complete code that I code.
composer.json
"require": {
"php": ">=5.6.4",
"elasticsearch/elasticsearch": "^6.0",
"laravel/framework": "5.3.*"
},
web.php
Route::get('/',array('uses' => 'ElasticSearch#addPeopleList'));
Controller
<?php
namespace App\Http\Controllers;
class ElasticSearch extends Controller
{
// elastic
protected $elastic;
//elastic cliend
protected $client;
public function __construct(Client $client)
{
$this->client = ClientBuilder::create()->build();
$config = [
'host' =>'localhost',
'port' =>9200,
'index' =>'people',
];
$this->elastic = new ElasticClient($config);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->$elastic);
exit;
}
}
But when I refresh the page then This page isn’t working i received this message and page not loaded one thing that I want to let you know that I made no changes in app.php file of configuration. Please eduacate to solve this issue.
if You want to instantiate an elastic client with some configuration, You should use method ClientBuilder::fromConfig(array $config).
In your case it should be
<?php
$client = ClientBuilder::fromConfig([
'hosts' => [ 'localhost:9200' ]
]);
As You can notice above hosts must be provided as array.
Also I'm not sure that Elasticsearch client that You use have ElasticClient class.
Also if You provided actual code from your controller than it contains an error. You should call class properties like that: print_r($this->client) (without $ near the property name).
Finaly your controller should looks like this:
<?php
namespace App\Http\Controllers;
use Elasticsearch\ClientBuilder;
class ElasticSearch extends Controller
{
/**
* #var \Elasticsearch\Client
*/
protected $client;
public function __construct()
{
$this->client = ClientBuilder::fromConfig([
'hosts' => [
'localhost:9200',
],
]);
}
public function addPeopleList(){
echo "<pre>";
print_r($this->client);
exit;
}
}
And to add a document to the index You need to call this command according to the official documentation
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
Official documentation can be found here https://github.com/elastic/elasticsearch-php
P.S. Sorry for my English. It is far from perfect.

PrestaShop 1.7 Add new resources and class

I created new resources with this code:
class WebserviceRequest extends WebserviceRequestCore {
public static function getResources(){
$resources = parent::getResources();
// if you do not have class for your table
$resources['test'] = array('description' => 'Manage My API', 'specific_management' => true);
$resources['categoryecommerce'] = array('description' => 'o jacie marcin', 'class' => 'CategoryEcommerce');
$mp_resource = Hook::exec('addMobikulResources', array('resources' => $resources), null, true, false);
if (is_array($mp_resource) && count($mp_resource)) {
foreach ($mp_resource as $new_resources) {
if (is_array($new_resources) && count($new_resources)) {
$resources = array_merge($resources, $new_resources);
}
}
}
ksort($resources);
return $resources;
}
}
And new class:
class CategoryEcommerceCore extends ObjectModelCore {
public $category_id;
public $category_core_id;
public static $definition = array(
'table' => "category_ecommerce",
'primary' => 'category_id',
'fields' => array(
'category_core_id' => array('type' => self::TYPE_INT),
)
);
protected $webserviceParameters = array();
}
Webservice is override properly. My class WebserviceRequest is copying to
/override/classes/webservice/WebserviceRequest
but class isn't copying to /override/classes/ when i installing my module.
How to add new resourcess with own logic ? I want to add categories within relation to my table.
Regards
Martin
As soon as there is literally nothing regarding the API except Webkul tutorial... I tried to implement the "Webkul's" tutorial, but also failed. However seems that it's better to use hooks instead of overrides. I used my "reverse engineering skills" to determine the way to create that API, so-o-o-o, BEHOLD! :D
Let's assume you have a custom PrestaShop 1.7 module. Your file is mymodule.php and here are several steps.
This is an install method wich allows you to register the hook within database (you can uninstall and reinstall the module for this method to be executed):
public function install() {
parent::install();
$this->registerHook('addWebserviceResources');
return true;
}
Add the hook listener:
public function hookAddWebserviceResources($resources) {
$added_resources['test'] = [
'description' => 'Test',
'specific_management' => true,
];
return $added_resources;
}
That specific_management option shows you are going to use WebsiteSpecificManagement file instead of database model file.
Create WebsiteSpecificManagement file, called WebsiteSpecificManagementTest (Test - is CamelCased name of your endpoint). You can take the skeleton for this file from /classes/webservice/WebserviceSpecificManagementSearch.php. Remove everything except:
setObjectOutput
setWsObject
getWsObject
getObjectOutput
setUrlSegment
getUrlSegment
getContent (should return $this->output; and nothing more)
manage - you should rewrite it to return/process the data you want.
Add
include_once(_PS_MODULE_DIR_.'YOURMODULENAME/classes/WebserviceSpecificManagementTest.php');
to your module file (haven't figured out how to include automatically).
Go to /Backoffice/index.php?controller=AdminWebservice and setup the new "Auth" key for your application, selecting the test endpoint from the permissions list. Remember the key.
Visit /api/test?ws_key=YOUR_KEY_GENERATED_ON_STEP_4 and see the XML response.
Add &output_format=JSON to your URL to see the response in JSON.
You have to use something like $this->output = json_encode(['blah' => 'world']) within manage method at WebsiteSpecificManagementTest.

Class not found, plugin working good

I made new plugin with informations find at this post: https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-cms-plugins/
I update composer.php and in vendor folder i got created files I see plugin phpclasses/evalmath in backend.
When on page i try do math operation:
function onStart() {
// instantiate a new EvalMath
$m = new EvalMath;
$m->suppress_errors = true;
// set the value of x
$m->evaluate('x = 3');
var_dump($m->evaluate('y = (x > 5)'));
}
I got error that Class 'EvalMath' not found Class is defined in file /plugins/phpclasses/evalmath/vendor/phpclasses/evalmath/evalmath.class.php What i am doing wrong?
in file /plugins/phpclasses/evalmath/composer.json
{
"require": {
"phpclasses/evalmath": ">=1.0.0"
},
"repositories": [
{
"type": "composer",
"url": "https:\/\/www.phpclasses.org\/"
},
{
"packagist": false
}
]
}
in file /plugins/phpclasses/evalmath/Plugin.php
<?php namespace phpclasses\evalmath;
use App;
use Config;
use System\Classes\PluginBase;
use Illuminate\Foundation\AliasLoader;
/**
*
* Class Plugin */
class Plugin extends PluginBase
{
/**
*
* Returns information about this plugin.
* #return array
*/
public function pluginDetails()
{
return ['name' => 'phpclasses/evalmath',
'description' => 'OctoberCMS plugin for demonstrating the use of Laravel Packages within October plugins',
'author' => 'hhh',
'icon' => 'icon-leaf'
];
}
/**
*
* Runs right before the request route */
public function boot()
{
// Setup required packages $this->bootPackages(); }
/**
*
* Boots (configures and registers) any packages found within this plugin's packages.load configuration value
* #see https://luketowers.ca/blog/how-to-use-laravel-packages-in-october-plugins
* #author Luke Towers octobercms#luketowers.ca
*/
public
function bootPackages()
{ // Get the namespace of the current plugin to use in accessing the Config of the plugin $pluginNamespace = str_replace('\', '.', strtolower(NAMESPACE));
// Instantiate the AliasLoader for any aliases that will be loaded
$aliasLoader = AliasLoader::getInstance();
// Get the packages to boot
$packages = Config::get($pluginNamespace . '::packages');
// Boot each package
foreach ($packages as $name => $options) {
// Setup the configuration for the package, pulling from this plugin's config
if (!empty($options['config']) && !empty($options['config_namespace'])) {
Config::set($options['config_namespace'], $options['config']);
}
// Register any Service Providers for the package
if (!empty($options['providers'])) {
foreach ($options['providers'] as $provider) {
App::register($provider);
}
}
// Register any Aliases for the package
if (!empty($options['aliases'])) {
foreach ($options['aliases'] as $alias => $path) {
$aliasLoader->alias($alias, $path);
}
}
}
}
}
}
in file /plugins/phpclasses/evalmath/classes/config.php
<?php
return [
// This contains the Laravel Packages that you want this plugin to utilize listed under their package identifiers
'packages' => [
'phpclasses/evalmath' => [
],
],
];
the most of the code in file /plugins/phpclasses/evalmath/Plugin.php(bootPackages()) is not nessesary if you dont have configs or additional providers or aliases
if its a laravel package you can use \App::register('\Your\LaravelPackage\ServiceProvider'); in the boot function
to register the package with the laravel Provider
and ad an alias for your package
$alias = \Illuminate\Foundation\AliasLoader::getInstance()->alias('YourAlias', '\Your\LaravelPackage\Facade');
if its not a laravel package try use the full namespace i think its \EvalMath if you use this package https://www.phpclasses.org/browse/file/11680.html

Slim Application Error: Respect\Validation\Validator

I get this error when trying to Validate my OrderForm.php. If someone followed Codecourse Shopping Cart Tutorial you may know why I get this error. Here is my code in some of my files that I think is most relevant to this error and of course the error.
Error:
Message: Class 'Respect\Validation\Validator' not found
File: PATH/cart/app/Validation/Forms/OrderForm.php
on 13
I will also post this image of my Directory Folders:
Directory Folder Image
OrderForm.php
<?php
namespace Cart\Validation\Forms;
use Respect\Validation\Validator as v;
class OrderForm
{
public static function rules()
{
return [
'email' => v::email(),
'name' => v::alpha(' '),
'address1' => v::alnum(' -'),
'address2' => v::optional(v::alnum(' -')),
'city' => v::alnum(' '),
'postal_code' => v::alnum(' '),
];
}
}
Validator.php
<?php
namespace Cart\Validation;
use Cart\Validation\Contracts\ValidatorInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Exceptions\NestedValidationException;
class Validator implements ValidatorInterface
{
protected $errors = [];
public function validate(Request $request, array $rules)
{
foreach ($rules as $field => $rule) {
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$this->errors[$field] = $e->getMessages();
}
}
$_SESSION['errors'] = $this->errors;
return $this;
}
public function fails()
{
return !empty($this->errors);
}
}
ValidatorInterface.php
<?php
namespace Cart\Validation\Contracts;
use Psr\Http\Message\ServerRequestInterface as Request;
interface ValidatorInterface
{
public function validate(Request $request, array $rules);
public function fails();
}
Edit: I just want to say that I changed:
use Respect\Validation\Validator as v;
to
use Cart\Validation\Validator as v;
And then I get a completely new error so that did that work.
It seems to me that you may be missing a dependency file such as respect/validation as some elements are installed during the video tutorials, I would recommend watching the video(s) concerning any of the validation routines, as the codecourse "Authentication with Slim 3:", installs additional addons/components with package managers such as composer, during the tutorial which may have been missed.
Well it tells you where the error is:
Message: Class 'Respect\Validation\Validator' not found
Path to that class is not valid, or that file is not on that path. I'm not completely sure but if you write it like you did use Respect\Validation\Validator as v; the final path will be current namespace plus that path Cart\Validation\Forms\Respect\Validation\Validator.
File: PATH/cart/app/Validation/Forms/OrderForm.php on 13
This second part is just were it triggered the error, on line 13 'email' => v::email(),.
Edit:
I just saw that image, the path should be use \App\Validation\Validator

Laravel Trying to Call Model Class Returns Not Found

This is in my routes.php :
Route::post('/', function()
{
$rules = array(
'email' => 'required|email'
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
echo "Not a valid e-mail";
}
else
{
$subscriber = Subscriber::where('email','=', Input::get('email') );
if ($subscriber)
{
echo "Email already exists";
}
else
{
Subscriber::create(array(
'email' => Input::get('email')
));
In my models folder, I have the following class defined:
<?php
class Subscriber extends Eloquent {
protected $table = 'subscribers';
protected $fillable = array('email');
public $timestamps = false;
}
?>
When I try and insert information into the database, it's telling me that Class 'Subscriber' is not found. Am I missing a connection of some sort?
Make sure you run composer dumpautoload when you create your model, so Laravel knows the new class exists.
Class files are automatically pulled in based on your autoload.php file. This file is dynamically generated via composer. You only have to run this once each time you create a new class file. If you modify an existing one, it's not needed.
Try composer dump-autoload and php artisan dump-autoload. It will regenerate all class files and class loader
Sorry to resurrect an old thread. You need to make sure that the file imports the class. Do this by adding the following line to the top of your routes.php file:
use App\Subscriber;
Note: This assumes that your generated class is in the App folder, which is the default.

Categories