Calling CakePHP v3 Controller Function From Custom External PHP File

343 Views Asked by At

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?

1

There are 1 best solutions below

4
Salines On

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