How laravel classes are included? - php

I want to run custom php code in laravel directly without using any routes or http requests..
I hope I can make it clear, I mean, like those online tools that runs php code by writing php code in browser, and then run it, and view result..
I found this handy project (Run-PHP-Code) to run PHP in browser directly, but I can't use models of my laravel project in PHP code..
How can I include laravel 's environment, so that I can for example:
$tag= new Tag;
where Tag is a model in laravel project, that would result into:
Fatal error: Class 'Tag' not found in D:\xampp\htdocs\widgetsRepository\app\controllers\Run-PHP-Code-master\index.php(49) : eval()'d code on line 3
Any idea? this would be very useful!
EDIT
I tried Brian suggestion at his answer, but I got this error now:
Call to a member function connection() on null
at vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
public static function resolveConnection($connection = null)
{
return static::$resolver->connection($connection);
}
so, I think I only need to get database sorted, then I can do experiments easily..

I've never tried to run code from a laravel project directly, I just copy and paste parts of the code into Run PHP Code.
That being said, it should be possible to run the code using the method taken from this StackOverflow question:
The Composer autoload script, to autoload all of your classes:
require __DIR__.'/../bootstrap/autoload.php';
And if you need things from the IoC container, you'll:
$app = require_once __DIR__.'/../bootstrap/start.php';
Then you will be able to do things like:
$post = Post::find(1);

Related

Laravel small standalone one-off script without artisan command?

I need to check something small in Laravel, so I just want to make a small script to check it.
I know that I can do it with
php artisan make:console ...
But It will add a file to the App/Console/Command, and I will need to update app/Console/Kernel.php. It means that I will have do commit it to source control, which is really not needed.
Is there a way to have a standalone laravel script which will give me access to the Laravel Components?
I am using Laravel 5.2, (make:command doesn't exists, only make:console)
Just an example for what I tried:
<?php
use App\User;
use DB;
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/..//bootstrap/app.php';
echo "hello world\n";
$res=User::where('id',5)->first();
echo "end!\n";
?>
But I am getting an error:
PHP Fatal error: Uncaught Error: Call to a member function connection() on null in /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3314
Stack trace:
#0 /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3280): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)
#1 /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1880): Illuminate\Database\Eloquent\Model->getConnection()
#2 /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1853): Illuminate\Database\Eloquent\Model->newBaseQueryBuilder()
#3 /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1823): Illuminate\Database\Eloquent\Model->newQueryWithoutScopes()
#4 /var/www/html/dpriceit/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(3524): Illuminate\Database\Eloquent\Model->newQuery()
UPDATE
I tried creating a console command
php artisan make:console MyTempTest
But when I do php artisan list I don't see its signature in the list of available commands.
To fix the error you're getting, boot up the application's kernel and handle the response like so
app\script.php
<?php
use App\User;
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
echo "hello world\n";
$res = User::find(5)->name;
var_dump($res);
echo "end!\n";
Then from a terminal, run php app/script.php
Result:
~/Sites/laravel (master ✗) ✹ ★ ᐅ php app/script.php
hello world
string(11) "Khalid Bins"
end!
When I want to try/test something in Laravel, I usually do one of three things:
If the "something" I want to try is a simple one-liner I use Tinker: artisan tinker. This gives you the fully booted Laravel Framework, ready to use any class or function you want. This is usually my go-to when I want to: Test a global helper function I just created; Create a model using a factory, to check if my factory is setup correctly; Check if my $casts array on a model is setup the right way;
Another scenario might involve a bit more code, maybe a few lines to retrieve some data from the database, mutate it and show it on a page. For this you can simply create a closure based route in the file routes/web.php:
Route::get('test-url', function () {
$user = User::where('email', 'user#example.com')->first();
$user->makeAdmin()->save();
// I can see on the page if the attributes have been changed, as a result of the makeAdmin() call.
return $user->getAttributes();
});
The same is possible for console routes. Add a structure like this in your routes/console.php file:
Artisan::command('test:functionality', function () {
$instance = new BusinessLogic();
$result = $instance->someVeryInterestingMethod();
dump($result);
});
You can then call this function from the command line with php artisan test:functionality. You can, of course, call the command whatever you like.
Then the last scenario; when I want to try something new (like a new package, library, plugin) and it will be more than a few lines of code. I create a new test class with php artisan make:test ThrowawayTest (or another randomly chosen name). I can then add a few lines of code and run it with PHPUnit. I have set my editor to launch the test that my cursor is on with the key-combination CTRL-T so that I can re-run it quickly when some code changed.
This means I can let some code stay in its function, and write a new function to elaborate on the things I just learned about the new package. When I am finished I can either leave the code and commit it to the repository, so that I can check the code later on when I need to use some of it again for production code. I can also throw away the test file if it seems like I won't need the code for reference in the future.
This last solution also gives me the added benefit of being able to use assert statements from PHPUnit.
Hope this gives you some insight on the different possibilities with the Laravel Framework when it comes to trying or testing out new stuff.

Error when Querying Parse with PHP

I am trying to use the Parse.com SDK with PHP. I have downloaded and installed the SDK and I have successfully created a test object.
However, when trying to retrieve an object with a basic query using the sample code provided in the Parse docs and when I try to run it I get:
Fatal Error: Class 'ParseQuery' not found in /home/jameshilton/public_html/index.php on line 109
I would have guessed that it is not linking to the SDK properly but everything else is working fine.
Any ideas what I'm doing wrong?
By looking at the code of the class ParseClient in on GitHub I can see that the classes are declared in the namespace parse. So when you need an object from the Parse library you need to select the namespace. This can be done in two ways.
At the top of your file write:
use \parse;
or when instantiating the class:
$query = new \parse\ParseQuery
And remember to make sure the files are included either through an autoloader (composer?) or manually using include or require.
Regards.

Call to undefined method ActiveRecord\Config::initialise() composer

Hey everyone I'm following a tutorial on Composer, I've installed ActiveRecord and I'm trying to create a database model. Whenever I load the page though I get this error: Call to undefined method ActiveRecord\Config::initialise()
Here's my setup file in index.php
require_once "vendor/php-activerecord/php-activerecord/ActiveRecord.php";
ActiveRecord\Config::initialise(function($cfg) {
//setting up a model (which is the representation of a table)
$cfg->set_model_directory('models');
$cfg->set_connections(array(
'development' => 'mysql://root:tutsplus#localhost/blog'
));
});
$posts = Post::all();
print_r($posts);
?>
And here's where I declare Post
class Post extends ActiveRecord\Model{}
I really cannot find the reason this isn't working, I actually did this instead to see if manually creating a new Post instance would fix the initialisation problem but it didn't, it had exactly the same error:
$post_class = new Post;
$posts = $post_class->all();
print_r($posts);
I'm really stumped on this one, I've usually managed to find something that fixes my problem on here but this is just nope. There is literally no difference to the tutorial code that I can see and I've checked it loads of times. Any help would be greatly appreciated.
(edit: the duplicate php-activerecord folders at the top isn't a code problem, the folder is actually duplicated and I haven't got round to moving the contents yet)
Point one: When using Composer, you are supposed to only include "vendor/autoload.php", and nothing else. Composer does the rest of autoloading for you.
Point two: It is called initialize with a Z, not S. You might simply have misspelled that method name.

PHP-FFMpeg prerequisites

I'm attempting to implement https://github.com/PHP-FFMpeg/PHP-FFMpeg
I copied the src/FFMpeg folder to my includes folder and made sure my autoloader knows where to find everything.
as a test I made a script that simply does:
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
I get:
Fatal error: Class 'Doctrine\Common\Cache\ArrayCache' not found in /var/www/php/include/FFMpeg/FFProbe.php on line 203
My question is: does PHP-FFMPeg require Doctrine, because that is not stated in the documentation. What version do I need? Are there other prerequisites?
I could create a new question for this, but I'm not sure if I should. I now have PHP-ffmpeg implemented. I'm using Laravel, however that should be irrelevant for this question. I'm trying to enable progress monitoring. It works, however I need to pass in an ID so I can update the correct key in memcache.
$id = 12345;
$format->on('progress', function ($audio, $format, $percentage) {
//this works perfect, but doesn't tell me which item is being updated
Cache::put("progress", $percentage, .25);
//this does not work as I am unable to pass in $id, if I add it as the 4th argument above it will display the number of threads or something
//Cache::put("{$id}_progress", $percentage, .25);
});
I need clarification on the "on" method. I looked through https://ffmpeg-php.readthedocs.org/en/latest/_static/API/ and was not able to figure out how this method works. Any help would be appreciated.
You should follow the recommended instructions in the README.
Composer is the easiest way to install PHP-FFMpeg dependencies
The "on" method called on the format is an implementation of EventEmitter.
As you can see here : https://ffmpeg-php.readthedocs.org/en/latest/_static/API/FFMpeg/Format/ProgressableInterface.html it extends the EventEmitterInterface of https://github.com/igorw/evenement.
If you're really interested about how it works under the hood, have a look at here :
The progress listener is created here : https://github.com/PHP-FFMpeg/PHP-FFMpeg/blob/master/src/FFMpeg/Format/Audio/DefaultAudio.php#L96 and added at execution here https://github.com/PHP-FFMpeg/PHP-FFMpeg/blob/master/src/FFMpeg/Media/Video.php#L151
This is actually possible because FFMpegDriver extends the Driver provided by https://github.com/alchemy-fr/BinaryDriver
Hope this helps :)

Writing a cron job using CodeIgniter CLI?

Hi I am facing some problems in writing a cron job using CI CLI way. My application has a controller name called manager.php in that there is method called check_status where I am gonna get all the order_ids using one model function. Ever order_id row had a status filed in database which either success or failure.
I have an api if i pass order_id to that it will tell whether order is successfully delivered or not. But here comes the problem I have below line in controller in the top.
<?php if(! defined('BASEPATH') ) exit("NO Direct Script Access Allowed"); ?>
So when i try to run method check_status from CLI in CI it gives me an error stating NO Direct Script Access Allowed.
This is the way i called above method php application/controllers/manager.php check_status
So i decided like this i created an another class file called cron_job.php in that i didn't keep the above error line "No Direct Script Access Allowed". I thought it will give access now when i try to run but it doesn't give an error and even output also.
This is the class which i created and method in that.
<?php
class Cron_job extends CI_Controller {
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
}
?>
I run this controller form CLI like this php application/controller/cron_job.php message
Note: I am in ROOT directory.
No Output at all. So i tried in another way like this php index.php application/controller/cron_job.php message
Now it gives me error stating that Error 404 page not found.
What i tried in another way now i created a file in views folder and in that i am calling old controller/method url like below.
$result = file_get_contents("http://application_path/controller/method");
echo $result;
Now i am getting output which i defined in the method check_status in manager.php controller.
But here comes another problem now after the above line i will get an array output which had all the order_ids.
I am gonna send this each id to a api to check status. If it is failure it will check whether it is delivered or not. If it's done i need to update that status in the database against that order_id. But now i am in view file, is it possible to call a model file from the view file or is there any way to do this.
Any help?
Note: There is no syntax errors in any controller or any method , which are fully verified and working normally when i am accessing using urls.
You need to read the CodeIgniter help section on Running via the Command Line. It's very easy. Your original approach was correct. But you do not call your controller method directly by its path, instead CD to your project root and then the call the index.php file with the controller and method as parameters.
// This is how you call CI via the command line.
// Use spaces between index.php and your arguments.
$ php index.php <controller> <method> [params]
// And in your instance
$ php index.php manager check_status [param1 param2 param3]
Depending on your host you may need to call the PHP version compiled for CLI.
the ci helper will help you in this.
1 ) Create a helper & create a function in it, that calls your model function
function getUserDetails($userId = '') {
$CI = & get_instance();
$getUserDetailsByUserId = $CI->user_model->getUserDetailsByUserId($userId);
return $getUserDetailsByUserId;
}
2) Now you can call getUserDetails($userId); in your view.

Categories