I'm trying to instantiate a controller and execute some methods but no result :(
jimport('joomla.application.component.controller');
$controller = JController::getInstance('com_shop');
$controller->my_method($arg1, $arg2);
Any idea?
This won't work try: JControllerLegacy::getInstance('CONTROLLERNAME') assuming that the controller you are calling follows the naming convention
<COMPONENTNAME><Controller><CONTROLLERNAME> for example WeblinksControllerWeblink
following is controller instantiation code taken form lender. And you don't need to use jimport in Joomla 3 extensions. Joomla auto load all classes starting with J prefix.
<?php // No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
//sessions
jimport( 'joomla.session.session' );
//load tables
JTable::addIncludePath(JPATH_COMPONENT.'/tables');
//load classes
JLoader::registerPrefix('Lendr', JPATH_COMPONENT);
//Load plugins
JPluginHelper::importPlugin('lendr');
//application
$app = JFactory::getApplication();
// Require specific controller if requested
if($controller = $app->input->get('controller','default')) {
require_once (JPATH_COMPONENT.'/controllers/'.$controller.'.php');
}
// Create the controller
$classname = 'LendrController'.$controller;
$controller = new $classname();
// Perform the Request task
$controller->execute();
Related
I am trying to use a library of classes within Laravel 8. I am having difficulty getting the classes to load correctly. I created a new folder within the App folder called DigiSigner, which is the external library's namespace.
App\DigiSigner
DigiSignerClient.php
\libs
BaseRequest.php
Branding.php
ClassLoader.php
Config.php
Curler.php
DigiSignerException.php
DigiSignerResponse.php
Document.php
DocumentField.php
DocumentFields.php
ExistingField.php
ExportObject.php
Field.php
SignatureRequest.php
Signer.php
I created a controller that looks like this
class SignPDFController extends Controller
{
public function getPDF()
{
$client = new DigiSignerClient('client_key');
$request = new SignatureRequest;
$request->setEmbedded(true);
$request->setSendEmails(false);
$template = Document::withID('document_id');
$template->setTitle('Site Title');
$request->addDocument($template);
$signer = new Signer('user#email.com');
$signer->setRole('Signer 1');
$template->addSigner($signer);
$initials = new ExistingField('key');
$initials->setContent('VS');
$signer->addExistingField($initials);
$response = $client->sendSignatureRequest($request);
foreach ($response->getDocuments() as $document) {
foreach ($document->getSigners() as $signer) {
$signDocumentUrl = $signer->getSignDocumentUrl();
}
}
}
}
The DigiSignerClient and the SignatureRequest classes seem to load fine, but the SignatureRequest needs to load the ExportObject class to extend it.
namespace App\DigiSigner;
use App\DigiSigner\libs\ExportObject;
class SignatureRequest extends ExportObject {
I end up with an error like the following.
Error Class 'App\DigiSigner\libs\ExportObject' not found
Namespaces and use are a little fuzzy for me. If someone can point me in the right direction, I would be delighted.
I believe I figured it out. All the files in the subdirectory needed the namespace changed to App\DigiSigner\libs.
Check ExportObject.php namespace.
I'm in the middle of adapting to namespaces and using spl_autoload_register(), but still struggling with understanding some aspects. For example, I have this current example working but I don't understand why there is an extra call made. Let me explain...
I have a "services" directory that houses service based classes:
services
div-services-debug.php
div-services-helper.php
div-services-etc.php
In my class I register my autoload function like so:
spl_autoload_register( array( $this, 'services' ) );
private function services( $class ) {
# If not a service don't bother
if (strpos($class, 'DIV\\services') === false) return;
$class = str_replace('\\', '-', strtolower($class));
if( is_file($this->path['services_dir'].$class.'.php') )
require $this->path['services_dir'].$class.'.php';
}
Example service looks something like this:
namespace DIV\services{
if ( ! class_exists( 'debug' ) ) :
class debug{
public static function scripts() {
...
}
}
endif;
}
I then implement a service like so:
DIV\services\debug::scripts();
Easy enough, but when running through some debugging on the autoloader method I'm noticing that with that call to the service I get 2 passes ($class = current class being passed through autoloader):
$class = DIV\services\helper
This I expected considering the call. But then I see another iteration
$class = helper
Why is this one call executing 2 attempts to autoload?
Both DIV\services\helper and helper are being called from the one implementation call. Is this how namespaces function? Any insight would be greatly appreciated, thanks!
#Xtremefaith, currently I am using this way
function __autoload($class){
spl_autoload_extensions('.php');
$normalized = __DIR__ .
DIRECTORY_SEPARATOR .
str_replace('\\', DIRECTORY_SEPARATOR, $class) .
spl_autoload_extensions();//normalize
if (!file_exists($normalized)) {
throw new Exception('Autoload Exception: File can not be loaded.');
} else {
require_once $normalized; //include file
}
}
spl_autoload_extensions('.php');
spl_autoload_register('__autoload');
And to call:
new \DIV\ClassName();
I hope this can help you in some way.
Just started development in the Phalcon PHP framework and am also pretty new to PHP in general. My question is on how to create a request with a route, which I believe I have done, and pass the parameters of the route to the controller action that is linked to the said route. Below I have included the three files that I have been working on and summarize what each one is supposed to do. I also have the end result and where my problem lies directly.
The first file is the index.php file that takes in all route requests for my site.
<?php
//Include all routes on site
foreach (glob("../app/routes/*.php") as $filename)
{
include $filename;
}
foreach (glob("../app/controllers/*.php") as $filename)
{
include $filename;
}
//Create routes and initialize routes
$router = new \Phalcon\Mvc\Router();
$router->mount(new PublicRoutes());
$router->mount(new ApiRoutes());
$router->mount(new AdminRoutes());
$router->handle();
$controller = $router->getControllerName();
$action = $router->getActionName();
$params = $router->getParams();
$di = new \Phalcon\DI\FactoryDefault();
$d = new Phalcon\Mvc\Dispatcher();
$d->setDI($di);
$d->setControllerName($router->getControllerName());
$d->setActionName($router->getActionName());
$d->setParams($router->getParams());
$controller = $d->dispatch();
The second file is the actual routes mounted in for my API call which I am testing everything out with.
<?php
class ApiRoutes extends Phalcon\Mvc\Router\Group
{
public function initialize()
{
//Basic api route for pixelpusher
$this->add(
"/addhawk/api/:action/:model/:params",
array(
"controller" => "api",
"action" => 1,
"model" => 2,
"params" => 3,
)
);
}
}
The third, and final file is the controller class for the API with the only action I am testing right now.
<?php
class ApiController extends \Phalcon\Mvc\Controller
{
public function handlerAction()
{
//Pull in parameters
echo "<h1>API Handler Entered</h1>";
$model = $this->dispatcher->getParam("model");
echo $model;
//Choose correct api based off of api param
if( $model == "grid" ) {
echo 'grid';
}
else if ( $model == "admin" ) {
echo 'admin';
}
else {
//No valid api must have been found for request
}
//Return result from api call
return true;
}
}
So, the url is "localhost/addhawk/api/handler/grate/view" which results in the following output in html courtesy of line 9 in the ApiController.
There is no print out of the $model variable as it should do. There is also no error so I have no idea why it's not printing. According to the documentation and every resource I have read online, all parameters should be available directly from each controller action thanks to the dispatcher and $di class or something similar. So my question is why can I not access the parameters if everything seems to be saying I should be able to?
I'm trying to create a small RESTful API for my database and I encountered a problem creating controller object dynamically based on user request, because all my code is using namespaces and just doing:
$api = new $controllerName($request);
Won't work. Because $controllerName would resolve to "ReadController", but is actually \controllers\lottery\ReadController hence the error
The whole part of defining the path to the class is:
if ($method === 'GET') {
$controllerName = 'ReadController';
// #NOTE: $category is a part of $_GET parameters, e.g: /api/lottery <- lottery is a $category
$controllerFile = CONTROLLERS.$category.'/'.$controllerName.'.php';
if (file_exists($controllerFile)) {
include_once($controllerFile);
$api = new $controllerName($request);
} else {
throw new \Exception('Undefined controller');
}
}
And the declaration of ReadController in core\controllers\lottery\ReadController.php
namespace controllers\lottery;
class ReadController extends \core\API {
}
Any ideas how to dynamically create the object?
Thanks!
$controllerName = 'controllers\lottery\ReadController';
new $controllerName($request);
Classes instantiated from strings must always use the fully qualified class name.
I have the following code in my zend application bootstrap file
protected function _initSessionId() {
$this->bootstrap( 'session' );
$opts = $this->getOptions();
$cache = $this->bootstrap( 'cachemanager' )
->getResource( 'cachemanager' )
->getCache( 'memcached' );
Zend_Db_Table_Abstract::setDefaultMetadataCache( $cache );
Zend_Registry::set( 'cache', $cache );
$defaultNamespace = new Zend_Session_Namespace();
if ( !isset( $defaultNamespace->initialized ) ) {
Zend_Session::regenerateId();
$defaultNamespace->initialized = true;
}
}
I want to know what the line $this->bootstrap('session') actually does. Which class/function does it instantiate and call?
How to bootstrap a resource
bootstrap(<resource_name>) tells to Zend_Bootstrap to init the specified resource before continue. Usually is used for init required dependencies before init the actual resource
The resource bootstrap can be declared in two ways.
A PHP method in the Bootstrap class.
function _init<Resource_name>() { ... }
Or in the ini file
resources.<resource_name>
in the last case (ini file) a class extending from Zend_Application_Resource_ResourceAbstract must be declared with the code for init the resource.
Session resource bootstrap
For the concrete case of bootstrap('session') by default use the init() method declared in Zend_Application_Resource_Session