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
Related
Problem
I created service TestService, that I use in colntroller file TestController in function test().
When I called test(), I got an error:
local.ERROR: Class 'App\TestService' not found {"userId":1,"exception":"[object] (Error(code: 0): Class 'App\TestService' not found at /Backend/app/Http/Controllers/TestController.php:8)
Code
TestController.php:
<?php
namespace App\Http\Controllers;
use App\TestService;
class TestController extends Controller
{
public function test()
{
return response()->json(TestService::getTest());
}
}
TestService.php:
<?php
namespace App;
use App\TestService;
class TestService
{
public static function getTest()
{
return "test";
}
}
What I tried
I checked all the names and they are correct.
When I wrote in the colntroller file use App\TestService;
I had autocomplete, so the service and name are visible.
I used these commands to refresh the files: php artisan serve and php artisan clear-compiled.
But it still doesn't work.
You have not correctly defined Namespace.
The namespace must be a directory path where you have created a file.
TestService.php:
<?php
namespace App\Services\Tests;
class TestService
{
public static function getTest()
{
return "test";
}
}
TestController.php:
<?php
namespace App\Http\Controllers;
use App\Services\Tests\TestService;
class TestController extends Controller
{
public function test()
{
//Call service class like.
return response()->json(TestService::getTest());
}
}
I'm using the latest 'master' branch of CodeIgniter 4
I have a Library that I'm trying to load automatically. Effectively, I want to have have 'one' index.php (that has meta, the basic html structure, etc) through which I can load views via my 'Template' Library.
My Library file: (~/app/Libraries/Template.php)
//class Template extends CI_Controller
class Template {
/* This throws an error, but I will open up a separte thread for this
public function __construct() {
parent::__construct();
}
*/
public function render($view, $data = array()) {
$data['content_view'] = $view;
return view('layout/index', $data);
}
}
I also have a controller set up:
class Locations extends BaseController
{
public function index()
{
return $this->template->render("locations/index", $view_data);
//return view('locations/index');
}
//--------------------------------------------------------------------
}
In ~/app/Config/ I added my Library
$classmap = [
'Template' => APPPATH .'/Libraries/Template.php'
];
I'm getting the following error:
Call to a member function render() on null
What am I doing wrong that's causing my library not to load?
In CI4 the BaseController is where you create things that you want to be used by multiple other controllers. Creating classes that extend others is so very easy in CI4.
It seems to me that the only thing you are missing is creating the Template class. (There are a couple of other minor things too, but who am I to point fingers?)
One big item that might be just that you don't show it even though you are doing it. That is using namespace and use directives. They are must-do items for CI 4.
Because of where you have put your files you don't need and should remove the following. See how I've used use which imports namespace already known to the autoloader.
$classmap = [
'Template' => APPPATH .'/Libraries/Template.php'
];
First, the BaseController
/app/Controllers/BaseController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use App\Libraries\Template;
class BaseController extends Controller
{
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [];
protected $template;
/**
* Constructor.
*/
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->template = new Template();
}
}
/app/Controllers/Locations.php
class Locations extends BaseController
{
public function index()
{
// set $viewData somehow
$viewData['someVar'] = "By Magic!";
return $this->template->render("locations/index", $viewData);
}
}
/app/Libraries/Template.php
<?php namespace App\Libraries;
class Template
{
public function render($view, $data = [])
{
return view($view, $data);
}
}
/app/Views/locations/index.php
This works as if... <strong><?= $someVar; ?></strong>
I know I haven't created exactly what you want to do. But the above should get you where you want to go. I hope so anyway.
It's tricky at first.
But I managed to run it successfully
Make sure you give it proper namespace
And then just "use" in your controller Location.
I dont change anything on Autoload.php.
app/Libraries/Template.php
<?php
namespace App\Libraries;
class Template {
public static function render($param) {
return 'Hello '.ucwords($param);
}
}
The proper way to call is put use App\Libraries\Template just before class Location extends BaseController
app/Controllers/Locations.php
<?php
namespace App\Controllers;
use App\Libraries\Template;
class Locations extends BaseController {
public function index() {
$template = new Template();
$renderedStuff = $template->render('World!');
echo $renderedStuff;
}
}
How does this work?
Notice in Template.php there is a namespace namespace App\Libraries;, so CI4 will automatically load that library properly also recognize the "Template" class. That is proper way to create CI4 libraries in my point of view.
How do we use that library?
Look at my example of Locations.php and then see this code use App\Libraries\Template;, that's how we call that libraries.
How do we call the function?
Look inside the index() function, here we call class Template using var $template = new Template();.
Then we call render() function in Template library with $template->render('World!');.
Just as simple as that.
I hope thats help, lemme know if it doesnt works. :)
Just a little hint, as my eye was hooked by the CI_Controller part.
You seems to use CI3 syntax within CI4, at least about loading the view, which translates to just:
$data = [
'title' => 'Some title',
];
echo view('news_template', $data);
See the CI3doc vs the CI4doc , the "static page" tutorial.
I have controller file that has a function login() that logs in(authenticates and returns a token) to some third party portal. Now i want to reuse that controller function in a custom command. Please suggest how to do so. My controller file looks like this-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class mmt extends Controller {
public function login() {
//code to login to third party portal
// returns a token after successful login
}
my custom command file located in app/Console/Commands looks like this-
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RcvSurveyEmails extends Command {
protected $signature = 'RcvSurveyEmails:name';
protected $description = 'command description here';
public function handle(){
//I need to use the login() function here and get the token.
}
?>
I search online for similar solution but could not fine any
You can do this In two Ways:
Method 1
Use Trait
trait LoginTrait{
public function Login(){
//put your code here
}
}
And After that you can use your function inside your class like below:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class mmt extends Controller {
use LoginTrait;//login is now available inside your class
//rest of your codes
}
And In Your Command It's Going to be like below:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RcvSurveyEmails extends Command {
use LoginTrait;//login Function is now avaiable inside your Command and you can call it
protected $signature = 'RcvSurveyEmails:name';
protected $description = 'command description here';
public function handle(){
login();//login function
}
}
Method 2
In case that your controller class doesn't have any special constructor you can create an instance from your controller inside your command and then call your method like below:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Http\Controllers\mmt;
class RcvSurveyEmails extends Command {
protected $signature = 'RcvSurveyEmails:name';
protected $description = 'command description here';
public function handle(){
$controller = new mmt();//your controller name
$controller->login();
}
}
I need use a PHP function to convert numbers to letters. I create a file named: converter.php in the folder “Controller”. I need call the function named “convertir_numero_letras($number)” insert in converter.php.
I call the function “convertir_numero_letras($number)” from the following controller:
public function convertirAction()
{
$number=1234;
$this->convertir_numero_letras($number);
return $this->render('contratos/mostrar_cifra.html.twig', array('numero_convertido' => $numero_convertido));
}
But this code not work. I obtain the following
error message:
Attempted to call an undefined method named "convertir_numero_letras" of class "BackendBundle\Controller\ContratosController".
As I can fix this?
you can create a folder inside bundle like yourBundel/Helper
and create you custom class in folder like ConverHelper.php
like this :
class ConvertHelper
{
public static function numero_letras($param)
{
return 'converted value';
}
}
and then you can call in any controller and any bundle like this:
yourBundle\helper\ConverterHelper::numero_letras('someting');
don't forget to add namespace of ConverterHelper to your contoller file
example:
// file: GRF/BlogBundle/Helper/ConverterHelper.php
<?php
namespace GRF\BlogBundle\Helper;
class ConverterHelper
{
public static function toNum($param)
{
return $param;
}
}
and usage in controller:
//file controller
<?php
namespace GRF\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PostController extends Controller
{
public function indexAction()
{
return new Response(\GRF\BlogBundle\Helper\ConverterHelper::toNum(32434));
}
}
I create an helper class where I put some functions. It works fine till I use an other class on it:
namespace Helpers;
class Helper {
public static function helloWorld()
{
return 'Hello World';
}
public static function accessPermission($role, $filtre)
{
$jointure_session = DB::table('jointure_session')
->where('session_type',$role)
->where($filtre,1)
->get();
foreach ($jointure_session as $value_jointure_session) {
return 'Allow '.$filtre;
}
}
}
I have an error because the DB class is not found.
Symfony \ Component \ Debug \ Exception \ FatalErrorException
Class 'Helpers\DB' not found
Any Idea?
Thank you in advance.
You have two options. Either you list the external clases in the top of your file with the world use:
<?php namespace Helpers;
use DB;
class Helper {
public static function helloWorld()
{
return DB::foo();
}
}
Either you scape the external classes with \:
<?php namespace Helpers;
class Helper {
public static function helloWorld()
{
return \DB::foo();
}
}
BTW, for simple functions you don't need to create a class. You can include your functions in a plain php file and load that file with composer. That way you avoid the namespace troubles you are having. i.e:
//File: resources/helpers.php
function helloWorld()
{
return DB::foo();
}
To load the file add this to your composer.json file
"autoload": {
"files": [
"resources/helpers.php"
],
},