how to use my own libraries in codeigniter 4? - php

I'm using codeigniter 4 but when I try to call my own library I get the error Undefined variable: utils.
here's my code:
/app/libraries/Utils.php
<?php
namespace App\Libraries;
class Utils
{
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
}
/app/Controllers/Users.php
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use App\Libraries\Utils;
class Users extends ResourceController
{
...
public function do_reset_password()
{
$utils = new Utils();
$str = $utils->generateRandomString(); // the error points to this line
...

You should place your file Utils.php in /app/Libraries
Do not create your own libraries directory in root project.

In your use line what happens if you do this:
use App\Libraries\Utils as MyUtils; and call $utils = new MyUtils instead?
Please also make sure your Libraries folder begins with a capital L.

Related

How to create a utils directory in laravel?

I want to create a directory for utils in Laravel 8. I have this but it doesn't work:
app/Utils/DateTime.php:
<?php
namespace App\Utils\DateTime;
const ISO8601_DATE_FORMAT = "Y-m-d\TH:i:s.uP";
function parseISO8601(string $time): \DateTime {
if ($time.endsWith("Z")) {
$time = $time.str_replace($time, "Z", "+00:00");
}
return \DateTime::createFromFormat(ISO8601_DATE_FORMAT, $time);
}
app/Http/Controllers/SearchController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
use function App\Utils\DateTime\parseISO8601 as parseISO8601;
class SearchController extends Controller
{
public function run(Request $request)
{
parseISO8601("2021-10-03T10:00:45.145126+01:00");
}
}
But I get an error:
Call to undefined function App\Utils\DateTime\parseISO8601()
What am I missing? It seems that it can't autoload DateTime for some reason. Do I need to manually configure an extra path somewhere in Laravel?
I changed it to a class and restarted PHP. It then gave me an error:
Class App\Utils\DateTime\DateTime located in ./app/Utils/DateTime.php does not comply with psr-4 autoloading standard. Skipping. which is explained here
I had incorrectly specified the namespace as App\Utils\DateTime even though the file was called DateTime.php. I just needed to change the namespace to App\Utils.

Calling CakePHP v3 Controller Function From Custom External PHP File

I have app using cakephp version 3.
How to call a function from a custom php file.
Assume I have a custom php file test.php. And I want to call cakephp function from controller file UrlController.php.
The test.php
<?php
error_reporting(E_ALL);
include 'path/to/UrlController.php';
echo json_decode(GetUrl());
The UrlController.php
<?php
namespace App\Controller;
use App\Controller\URLController;
use Cake\Event\Event;
use Cake\I18n\Time;
use Cake\Network\Exception\NotFoundException;
use Cake\ORM\TableRegistry;
class LinksController extends URLController
{
public function GetUrl()
{
$link = $this->Links->newEntity();
$data = [];
$link = $this->Links->patchEntity($link, $data);
if ($this->Links->save($link)) {
$content = [
'status' => '200',
'message' => 'success',
'url' => 'https://google.com'
];
$this->response->body(json_encode($content));
return $this->response;
}
}
}
When tried to include app index.php and bootstrap.php it's still not working.
Edited test.php based on #Salines answer but still not working
<?php
namespace App\test;
error_reporting(E_ALL);
use App\Controller\URLController;
class Test extends URLController
{
public function custom()
{
$this->getUrl(); // call function from UrlController
}
}
Error: "PHP Fatal error: Class 'App\Controller\URLController' not found in /../public_html/test/test.php on line 7"
My test file located at /absolute/path/public_html/test/test.php, what should I put in the namespace?
In same way as you use Links Controller
test.php
<?php
namespace App\path_to_folder_where_is_your_test_php;
use App\Controller\URLController;
class Test extends UrlController
{
pubic function custom()
{
$this->getUrl(); // call function from UrlController
}
Or in PHP without class
$newUrl = new \App\Controller\URLController();
$result = $newUrl->getUrl();
However, you do not comply with the MVC standard

Laravel : Class 'App\Services\OvhApiHandlerClass' not found

I'm starting Laravel and i'm trying to create an external class to use like a 'Library'.
I've searched a lot and came up with this solution :
I created a folder 'Services' in 'App' and made a class file like so :
App/Services/OvhApiHandlerClass.php
This file looks like so :
<?
namespace App\Services;
use App\OvhBill;
use App\OvhBillDetail;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Ovh\Api;
class OvhApiHandlerClass
{
public function ovh_get_bills(string $consumer_key, $from = null, $to = null)
{
// Do something
}
}
So now i want to use this class inside a controller.
But i'm getting an error saying my class does not exist.
Here is my Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Services\OvhApiHandlerClass;
class OperationsController extends Controller
{
public function index()
{
$from = new \Carbon\Carbon('first day of January 2019');
$ovhHandler = new OvhApiHandlerClass();
$ovhHandler->ovh_get_bills('K87u3410p89ijKLao', $from);
return view('operations.index');
}
}
I already did, of course
composer dump-autoload
I'm kinda lost, what am i missing?
Thank you very much for your time !

How to solve namespaces problems in php tinker?

I have the following code:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Enemy extends Model
{
// ...
static function fight($id)
{
if(Enemy::calcDist($id))
{
$model = Enemy::find($id);
if($model->status == 1)
{
$model->status = 2;
$model->save();
}
}
}
}
When I try to do App\Enemy::fight(1) in php tinker it shows error:
"Class 'App\App\Enemy' not found".
I tried with "calcDist($id)", with "self::calcDist($id)", also at find($id) function, but no result.
How I can solve this?
Edit: I found the problem; that error comes from another part of code...
When you are in namespace App you dont need to use App\Enemy in your call.
Simply use Enemy::fight(1), or use the absolute namespace \App\Enemy::fight(1)
When you use a static class by his name, the engine search the class into the current namespace. If no namespace is given, then it uses the namespace "\".
namespace App;
Enemy::fight(1); // \App\Enemy::fight(1) ok
App\Enemy::fight(1); // \App\App\Enemy::fight(1) wrong

How to resolve a controller with make parameter in laravel 5?

Previously I could do something like this:
/var/www/laravel/app/Http/Controllers/HelloController.php
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Hello\Hello as Hello;
class HelloController extends Controller {
public function index() {
$o = new Hello;
$o = new Hello('changed1','changed1');
var_dump($o);
}
}
/var/www/laravel/app/Models/Hello
<?php namespace App\Models\Hello;
use Illuminate\Database\Eloquent\Model\Hello.php;
class Hello extends Model
{
public function __construct($one='default1', $two='default2')
{
echo "First Param: $one","\n<br>\n";
echo "Second Param: $two","\n<br>\n";
echo "\n<br>\n";
}
}
routes.php
Route::get('tutorial', function() {
$app = app();
$app->make('Hello');
});
Instantiating without make works, but this now brings an error:
ReflectionException in Container.php line 776: Class Hello does not exist
What do you think I am missing in here?
Because your class has a namespace of App\Models\Hello, you must use the namespace of it when trying to instantiate the class. Therefore, your code should be like this:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
});
To expand a bit in the answer, you can remove the make() method call and just use the app() helper, and you'll end up with the same result:
Route::get('tutorial', function() {
$app = app();
$app->make('App\Models\Hello\Hello');
// you can achieve the same with the
// `app()` helper using less characters :)
app('App\Models\Hello\Hello');
});

Categories