Repeat function in Laravel / PHP Class in one shared function - php

With the following code, how do I place the on_stats function in one area? So it can be shared and called in all functions on this page instead of copying and pasting the same code over and over again. Also how do I declare $logger just once instead of over and over again.
class API extends Controller
{
public function __construct() {
}
public function api_call1() {
$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$logger = new Logger('View Logs');
$logger->pushHandler(new StreamHandler(storage_path() . '/logs/api_log.log', Logger::INFO));
$res = $client->get($this->url . "/my/url/", [
'on_stats' => function (TransferStats $stats) use ($logger) {
$logger->info('Request' . $stats->getRequest()->getMethod() .
'Response' . $stats->getResponse()->getStatusCode() .
'Tx Time' . $stats->getTransferTime()
);
}
]);
$response = Response::make($res->getBody(), 200);
$response->header('Content-Type', 'application/json');
return $response;
}
public function api_call2() {
$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$logger = new Logger('View Logs');
$logger->pushHandler(new StreamHandler(storage_path() . '/logs/api_log.log', Logger::INFO));
$res = $client->get($this->url . "/my/url2/", [
'on_stats' => function (TransferStats $stats) use ($logger) {
$logger->info('Request' . $stats->getRequest()->getMethod() .
'Response' . $stats->getResponse()->getStatusCode() .
'Tx Time' . $stats->getTransferTime()
);
}
]);
$response = Response::make($res->getBody(), 200);
$response->header('Content-Type', 'application/json');
return $response;
}
}

From my viewpoint, it would be a great idea to:
Declare a class property as $logger
Move logger initialization to the constructor
Rewrite the "on_stats" method as a class method, say logEvent(TransferStats $stats) using $this->logger, this way you can avoid using "use" keyword
Pass the client event "on_stats" as a standard PHP callable array:
['on_stats' => [$this, 'logEvent']]

Related

GuzzleHTTP Request Error for VismaSign PHP

This is the error I am receiving from function authMiddleware() with GuzzleHttp. I am using this for VismaSign and receiving these errors. I am not sure what exactly is the issue:
Uncaught TypeError: Argument 1 passed to
app\handlers\integrations\VismaSign::authMiddleware() must be an
instance of GuzzleHttp\Psr7\Request, instance of
GuzzleHttp\HandlerStack given.
Here is my code:
<?php
namespace app\handlers\integrations;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
class VismaSign {
const API_URL = "https://sign.visma.net/api/v1/";
const CLIENT_IDENTIFIER = "ddf58116-6082-4bfc-a775-0c0bb2f945ce";
const SECRET_KEY = "jp7SjOOr4czRTifCo30qx0sZAIw9PW+vVpsbP09pQaY=";
private $client;
private $clientHandler;
public function __construct() {
$this->client = new Client();
$this->clientHandler = $this->client->getConfig('handler');
}
public function authMiddleware(Request $request) {
$request = new Request('POST', 'https://httpbin.org/post');
//return $request->withHeader('Authorization', $this->authorizationHeader(self::CLIENT_IDENTIFIER, base64_decode(self::SECRET_KEY), $request->getMethod(), (string)$request->getBody(), ($request->getHeader('Content-Type') ?: [''])[0], $request->getHeader('Date')[0], $request->getUri()->getPath() . ($request->getUri()->getQuery() ? '?' . $request->getUri()->getQuery() : '')));
return $request->withHeader(
'Authorization',
$this->authorizationHeader(
self::CLIENT_IDENTIFIER,
base64_decode(self::SECRET_KEY),
$request->getMethod(),
(string)$request->getBody(),
($request->getHeader('Content-Type') ?: [''])[0],
$request->getHeader('Date')[0],
$request->getUri()->getPath() .
($request->getUri()->getQuery() ? '?' . $request->getUri()->getQuery() : '')
)
);
}
private function authorizationHeader($username, $secret, $method, $body, $contentType, $date, $path) {
$str = join("\n", [
$method,
base64_encode(hash('md5', $body, true)),
$contentType,
$date,
$path
]);
$header = 'Onnistuu ' . $username . ':' . base64_encode(hash_hmac('sha512', $str, $secret, true));
return $header;
}
public function createDocument() {
$response = $this->client->request('POST', self::API_URL . 'document/', [
'json' => [
'document' => [
'name' => 'Test document ' . date(\DateTime::ATOM),
]
],
'headers' => [
'Date' => date('r'),
],
'handler' => $this->authMiddleware($this->clientHandler),
]);
if ($response->getStatusCode() !== 201) {
echo 'Could not create document';
return;
}
return $response->getHeader('Location')[0];
}
}
in your constructor create add new object request of class GuzzleHttp\Psr7\Request:
public function __construct() {
$this->request = new Request();
$this->client = new Client();
$this->clientHandler = $this->client->getConfig('handler');
}
and in your createDocument method pass this only:
'handler' => $this->authMiddleware($this->request),
because your error clearly says
must be an instance of GuzzleHttp\Psr7\Request, instance of GuzzleHttp\HandlerStack

How to add my function and use it properly in controller?

I have 'sendsms' function which i used it in one of my controllers and worked fine. now what i need to know how i can make class reference of this code to use it in other controllers, instead of copy/paste whole code in all controllers.
In other Q/A they mentioned about only creating reference but i wanted to do it properly like using constructor or etc, not just doing things work, i want to do it like real-world project.
Here's the code in controller :
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|string|min:6',
'gametype' => 'required|string|min:3',
'description' => 'required|string|min:1|max:180',
'price' => 'required|numeric|min:4',
'buyyer_id' => 'required|numeric|min:1'
// 'seller_id' => 'required|numeric|min:1'
]);
// return RequestModel::create([
// 'title' => $request['title'],
// 'description' => $request['description'],
// 'gametype' => $request['gametype'],
// 'price' => $request['price'],
// 'buyyer_id' => $request['buyyer_id'],
// 'seller_id' => Auth::user()->id,
// ]);
//
$requestModel = new RequestModel;
// store
$requestModel->title = $request['title'];
$requestModel->description = $request['description'];
$requestModel->gametype = $request['gametype'];
$requestModel->price = $request['price'];
$requestModel->buyyer_id = $request['buyyer_id'];
$requestModel->seller_id = Auth::user()->id;
$requestModel->save();
return $this->sendSms($request['title'], $request['gametype']);
}
// I want to use this code in another class to use it in all controllers without copy/paste it.
function sendSms($reqid, $recgametype) {
//Send sms to getway
//implement later.
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$reqid. " ) for ( " .$recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
$client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
echo $ex->faultstring;
}
}
I'm right now learning and I'm beginner at this so help to understand how to make it work properly. Thanks.
You can create a separate SMS class like :
<?php
namespace App;
class SMS {
private $reqid;
private $recgametype;
public function __construct($reqid, $recgametype)
{
$this->reqid = $reqid;
$this->recgametype = $recgametype;
}
public function send()
{
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$this->reqid. " ) for ( " .$this->recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
return $client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
throw new \Exception('SMS sending failed')
}
}
}
And then inside controller or wherever you would need :
public function sendSms($reqid, $recgametype) {
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
}
You can also create custom exception like SMSSendingFailedException and throw it instead of standard \Exception inside send() function.
That will help you to send appropriate response in controller like :
public function sendSms($reqid, $recgametype) {
try{
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
return response()->json('message' => 'SMS sent successfully', 200);
}
catch(SMSSendingFailedException $e){
return response()->json('message' => 'SMS sending failed', 500);
}
}
Then to go one step further, you can use concept of laravel facade if you need it all over the project with a quick class alias.

Multi-threaded downloading files with Guzzle HTTP client: EachPromises vs Pool objects

for testing purposes, I have an array of 2000 image URIs (strings) with I download asynchronously with this functions. After some googling & testing & trying I've come up with 2 functions that both of them work (well to be honest downloadFilesAsync2 throws a InvalidArgumentException at the last line).
The function downloadFilesAsync2 is based on the class GuzzleHttp\Promise\EachPromise and downloadFilesAsync1 is based on the GuzzleHttp\Pool class.
Both functions download pretty well the 2000 files asynchronously, with the limit of 10 threads at the same time.
I know that they work, but nothing else. I wonder if someone could explain both aproaches, if one is better than the other, implications, etc.
// for the purpose of this question i've reduced the array to 5 files!
$uris = array /
"https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120.jpg",
"https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-01.jpg",
"https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-02.jpg",
"https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-03.jpg",
"https://cdn.enchufix.com/media/catalog/product/u/n/unix-48120-04.jpg",
);
function downloadFilesAsync2(array $uris, string $dir, $overwrite=true) {
$client = new \GuzzleHttp\Client();
$requests = array();
foreach ($uris as $i => $uri) {
$loc = $dir . DIRECTORY_SEPARATOR . basename($uri);
if ($overwrite && file_exists($loc)) unlink($loc);
$requests[] = new GuzzleHttp\Psr7\Request('GET', $uri, ['sink' => $loc]);
echo "Downloading $uri to $loc" . PHP_EOL;
}
$pool = new \GuzzleHttp\Pool($client, $requests, [
'concurrency' => 10,
'fulfilled' => function (\Psr\Http\Message\ResponseInterface $response, $index) {
// this is delivered each successful response
echo 'success: '.$response->getStatusCode().PHP_EOL;
},
'rejected' => function ($reason, $index) {
// this is delivered each failed request
echo 'failed: '.$reason.PHP_EOL;
},
]);
$promise = $pool->promise(); // Start transfers and create a promise
$promise->wait(); // Force the pool of requests to complete.
}
function downloadFilesAsync1(array $uris, string $dir, $overwrite=true) {
$client = new \GuzzleHttp\Client();
$promises = (function () use ($client, $uris, $dir, $overwrite) {
foreach ($uris as $uri) {
$loc = $dir . DIRECTORY_SEPARATOR . basename($uri);
if ($overwrite && file_exists($loc)) unlink($loc);
yield $client->requestAsync('GET', $uri, ['sink' => $loc]);
echo "Downloading $uri to $loc" . PHP_EOL;
}
})();
(new \GuzzleHttp\Promise\EachPromise(
$promises, [
'concurrency' => 10,
'fulfilled' => function (\Psr\Http\Message\ResponseInterface $response) {
// echo "\t=>\tDONE! status:" . $response->getStatusCode() . PHP_EOL;
},
'rejected' => function ($reason, $index) {
echo 'ERROR => ' . strtok($reason->getMessage(), "\n") . PHP_EOL;
},
])
)->promise()->wait();
}
First, I will address the InvalidArgumentException within the downloadFilesAsync2 method. There are actually a pair of issues with this method. Both relate to this:
$requests[] = $client->request('GET', $uri, ['sink' => $loc]);
The first issue is the fact that Client::request() is a synchronous utility method which wraps $client->requestAsync()->wait(). $client->request() will return an instance of Psr\Http\Message\ResponseInterface, as a result $requests[] will actually be populated with ResponseInterface implementations. This is what, ultimately causes the InvalidArgumentException as the $requests does not contain any Psr\Http\Message\RequestInterface's, and the exception is thrown from within Pool::__construct().
A corrected version of this method should contain code which looks more like:
$requests = [
new Request('GET', 'www.google.com', [], null, 1.1),
new Request('GET', 'www.ebay.com', [], null, 1.1),
new Request('GET', 'www.cnn.com', [], null, 1.1),
new Request('GET', 'www.red.com', [], null, 1.1),
];
$pool = new Pool($client, $requests, [
'concurrency' => 10,
'fulfilled' => function(ResponseInterface $response) {
// do something
},
'rejected' => function($reason, $index) {
// do something error handling
},
'options' => ['sink' => $some_location,],
]);
$promise = $pool->promise();
$promise->wait();
To answer your second question, "What is the difference between these two methods", the answer is simply, there is none. To explain this, let me copy and paste Pool::__construct():
/**
* #param ClientInterface $client Client used to send the requests.
* #param array|\Iterator $requests Requests or functions that return
* requests to send concurrently.
* #param array $config Associative array of options
* - concurrency: (int) Maximum number of requests to send concurrently
* - options: Array of request options to apply to each request.
* - fulfilled: (callable) Function to invoke when a request completes.
* - rejected: (callable) Function to invoke when a request is rejected.
*/
public function __construct(
ClientInterface $client,
$requests,
array $config = []
) {
// Backwards compatibility.
if (isset($config['pool_size'])) {
$config['concurrency'] = $config['pool_size'];
} elseif (!isset($config['concurrency'])) {
$config['concurrency'] = 25;
}
if (isset($config['options'])) {
$opts = $config['options'];
unset($config['options']);
} else {
$opts = [];
}
$iterable = \GuzzleHttp\Promise\iter_for($requests);
$requests = function () use ($iterable, $client, $opts) {
foreach ($iterable as $key => $rfn) {
if ($rfn instanceof RequestInterface) {
yield $key => $client->sendAsync($rfn, $opts);
} elseif (is_callable($rfn)) {
yield $key => $rfn($opts);
} else {
throw new \InvalidArgumentException('Each value yielded by '
. 'the iterator must be a Psr7\Http\Message\RequestInterface '
. 'or a callable that returns a promise that fulfills '
. 'with a Psr7\Message\Http\ResponseInterface object.');
}
}
};
$this->each = new EachPromise($requests(), $config);
}
now if we compare that to an a simplified version of the code within the downloadFilesAsync1 method:
$promises = (function () use ($client, $uris) {
foreach ($uris as $uri) {
yield $client->requestAsync('GET', $uri, ['sink' => $some_location]);
}
})();
(new \GuzzleHttp\Promise\EachPromise(
$promises, [
'concurrency' => 10,
'fulfilled' => function (\Psr\Http\Message\ResponseInterface $response) {
// do something
},
'rejected' => function ($reason, $index) {
// do something
},
])
)->promise()->wait();
In both examples, there is a generator which yields promises that resolve to instances of ResponseInterface and that generator along with the configuration array (fulfilled callable, rejected callable, concurrency) is also fed into a new instance of EachPromise.
In summary:
downloadFilesAsync1 is functionally the same thing as using Pool only without the error checking that has been built into Pool::__construct().
There are a few errors within downloadFilesAsync2 which will cause the files to be downloaded in a synchronous fashion prior to receiving an InvalidArgumentException when the Pool is instantiated.
My only recommendation is: use whichever feels more intuitive for you to use.

Can not access my pages using acl and custom dispatcher

I'm currently using Phalcon 3.3 / PHP 7.2 (Ubuntu 18.04 LTS / Windows 10)
I created a custom SecurityPlugin file to verify user permission to access routes. I've defined my roles, resources and permission using Phalcon's ACL.
Here's my SecurityPlugin class
<?php
use Phalcon\Acl;
use Phalcon\Acl\Resource;
use Phalcon\Acl\Role;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;
/**
* Class SecurityPlugin
*
* This is the security plugin that makes sure users access the modules they are assigned to
*
*/
class SecurityPlugin extends Plugin
{
private function _getAcl()
{
if(!isset($this -> persistent -> acl))
{
$acl = new AclList();
$acl -> setDefaultAction(Acl::DENY);
//Add Roles
$roles = [
'base_acc' => new Role(
'BaseAcc',
'This role represents the standard users that are allowed on the platform'
),
'guest' => new Role(
'Guest',
'This is the default role assigned to users that are not logged in'
)
];
//Register Roles
foreach ($roles as $role) {
$acl -> addRole($role);
}
//Add Standard User Resources
$standardResources = [
'store' => ['index']
];
//Add Public Resources
$publicResources = [
'index' => ['index'],
'auth' => ['index', 'login', 'logout', 'register', 'confirmEmail', 'continueReg', 'finishReg', 'verifyPasswordToken', 'forgotPassword', 'updatePassword'],
'errors' => ['show404', 'show503', 'errorConfirm']
];
//Register Standard User Resources
foreach ($standardResources as $resource => $actions)
{
$acl -> addResource(new Resource($resource), $actions);
}
//Register Public Resources
foreach ($publicResources as $resource => $actions)
{
$acl -> addResource(new Resource($resource), $actions);
}
//Register Public Resources to all roles
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions){
foreach($actions as $action){
$acl -> allow($role -> getName(), $resource, $action);
}
}
}
//Register Standard Resources to standard User Role
foreach ($standardResources as $resource => $actions){
foreach($actions as $action){
$acl -> allow('BaseAcc', $resource, $action);
}
}
$this -> persistent -> acl = $acl;
}
return $this -> persistent -> acl;
}
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
$auth = $this->session->get('auth');
if (!$auth){
$role = 'Guests';
} else {
$role = 'BaseAcc';
}
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
$acl = $this->_getAcl();
if (!$acl->isResource($controller)) {
$dispatcher->forward([
'controller' => 'errors',
'action' => 'show404'
]);
return false;
}
$allowed = $acl->isAllowed($role, $controller, $action);
if (!$allowed) {
$dispatcher->forward([
'controller' => 'errors',
'action' => 'show401'
]);
//$this->session->destroy();
return false;
}
//Checks thr current user role
//$roles = [];
/*$auth = $this -> session -> get('auth');
if(!$auth)
{
$role = 'Guest';
}
else
{
$role = 'BaseAcc';
}
$acl = $this -> _getAcl();
$controller = $dispatcher -> getControllerName();
$action = $dispatcher -> getActionName();
$lastController = $dispatcher ->getLastController();
if(!$acl -> isResource($controller))
{
$dispatcher -> forward([
'controller' => 'errors',
'action' => 'show404'
]);
return false;
}
if(!$acl -> isAllowed($role, $controller, $action))
{
$dispatcher -> forward([
'controller' => 'errors',
'action' => 'show503'
]);
return false;
}*/
}
}
My part of my application bootstrap:
<?php
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');
error_reporting(E_ALL);
use Phalcon\Mvc\View as ViewEngine;
use Phalcon\Mvc\Model\MetaData\Files as MetaDataAdapter;
use Phalcon\Mvc\Application as AppEngine;
use Phalcon\Flash\Session as FlashService;
use Phalcon\Flash\Direct as FlashDirect;
use Phalcon\Session\Adapter\Files as SessionHandler;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
//use Phalcon\Logger\Adapter\File as LogService;
use Phalcon\Logger\Factory as LogFactory;
try{
//Try our Debugger
// = new Phalcon\Debug();
//$debug -> listen(true, true);
//Application Loader
$loader = new Phalcon\Loader();
//Register Working Directories
$loader -> registerDirs([
APP_PATH . '/controllers',
APP_PATH . '/config',
APP_PATH . '/models',
APP_PATH . '/cache',
APP_PATH . '/plugins',
BASE_PATH . '/vendor',
]);
//Register Namespaces
$loader -> registerNamespaces([
//'AgroTech\Models' => APP_PATH . '/models',
'AgroTech\Plugins' => APP_PATH . '/plugins'
]);
//Register Loader
$loader -> register();
// Use composer autoloader to load vendor classes
require_once BASE_PATH . '/vendor/autoload.php';
$di = new Phalcon\Di\FactoryDefault();
...
$di -> set('dispatcher', function() use ($di){
$eventsManager = $di->getShared('eventsManager');
//Bind our Custom Event Handlers
$eventsManager -> attach('dispatch:beforeExecuteRoute', new SecurityPlugin());
$eventsManager -> attach('dispatch:beforeException', new NotFoundPlugin());
//xdebug_print_function_stack();
$dispatcher = new Phalcon\Mvc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
...
$app = new AppEngine($di);
$response = $app -> handle();
$response -> send();
} catch(Phalcon\Exception $e){
echo "Exception: " . $e -> getMessage();
echo '<pre>' . $e -> getTraceAsString() . '</pre>';
}
However, binding the event 'dispatch:beforeExecuteRoute' with my SecurityPlugin gives me a 503 error. Disabling it makes all my pages acessible. And also, disabling my NotFoundPlugin (which handles invalid routes), I get a Dispatcher Cyclic routing error
Is there something I'm doing wrong?
Note: I based my SecurityPlugin implementation off https://github.com/phalcon/invo
What i can say? Just debug it with xdebug or even var_dumps and that's it? Check what is your $auth, controller, action etc in beforeExecuteRoute method and check what isAllowed is returning and how your acl object looks like after creating it and you will find your mistake easy.

Phalcon 3 and PHP 7 breaking the existing site

My problem started right after I upgraded PHP to Version 7 and Phalcon to Version 3.
Problem
I m getting blank page, no error messages (Error is turned on), no `500 Internal server' error in console. The site used to work flawlessly before.
I have following controller IndexController.php
<?php
namespace RealEstate\Property\Controllers;
use \Phalcon\Mvc\Controller;
use \Phalcon\Mvc\View;
use RealEstate\Common\Models as CommonModels;
class IndexController extends Controller
{
public function initialize(){
//Code here
}
public function indexAction(){
$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
$this->view->setVar("total_properties", $this->utils->getTotalProperties());
$this->view->pick("index");
echo "HELLO WORLD";
}
}
The index action doesnot render anything, but yes HELLO WORLD is printed, so there seems there is no errors in code above that line.
My bootstrap index.php
<?php
namespace RealEstate;
use \Phalcon\Mvc\Application;
use \Phalcon\DI\FactoryDefault;
use \Phalcon\Loader;
use \Phalcon\Mvc\Router;
use \Phalcon\Mvc\View;
use \Phalcon\Mvc\Dispatcher;
use \Phalcon\Events\Manager as EventManager;
use \Phalcon\Assets\Manager as Assets;
use \Phalcon\Mvc\Url as UrlProvider;
use \Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use \Phalcon\Flash\Session as FlashSession;
use \Phalcon\Session\Adapter\Files as SessionAdapter;
use \Phalcon\Http\Response\Cookies;
//use \Phalcon\Session\Adapter\Files as Session;
class MyApplication extends Application
{
const DEFAULT_MODULE = "property";
private $prConfig;
/**
* Register the services here to make them general or register in the ModuleDefinition to make them module-specific
*/
protected function _registerServices()
{
try{
$config = include "../apps/config/config.php";
$di = new FactoryDefault();
$loader = new Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerDirs(
array(
__DIR__ . '/../apps/library/',
__DIR__ . '/../apps/plugins/'
)
);
$loader->registerNamespaces(array(
'RealEstate\Common\Plugins' => '../apps/plugins/',
'RealEstate\Common\Models' => '../apps/common/models/',
'RealEstate\Library\Pagination' => '../apps/library/',
'Facebook' => __DIR__.'/../apps/plugins/FacebookSDK/'
));
$loader->registerClasses(array(
"FacebookLib" => __DIR__.'/../apps/library/FacebookLib.php',
"Facebook" => __DIR__.'/../apps/plugins/FacebookSDK/autoload.php',
"MobileDetect" => __DIR__.'/../apps/library/MobileDetect.php'
));
$loader->register();
$di->set('config', $config, true);
//Register assets like CSS and JS
$di->set("assets",function(){
$assets = new Assets();
$cdnUrl = $this->cdnurl;
//Add CSS to collection. "true" means we're using base url for css path
$assets->collection('css')->addCss($cdnUrl.'assets/css/frontend/combined.css?v=44');
$assets->collection('footer')->addJs($cdnUrl.'assets/js/frontend/combined.js?v=44', false);
return $assets;
});
$this->prConfig = $config;
//register base url
$di->set('baseurl', function() use ($config){
$url = $config->application->baseUri;
return $url;
});
//register CDN url
$di->set('cdnurl', function() use ($config){
$url = $config->application->cdnUri;
return $url;
});
//Module Information
$di->set('appconfig', function() use ($config){
$appconfig = $config->application;
return $appconfig;
});
//Register URL helper
//set base url
$di->set('url', function() use ($config){
$url = new UrlProvider();
$url->setBaseUri($config->application->baseUri);
return $url;
});
//Register dependency for a database connection
$di->setShared('db', function() use ($config){
return new DbAdapter(array(
"host" => $config->database->host,
"username" => $config->database->username,
"password" => $config->database->password,
"dbname" => $config->database->dbname
));
});
//Register and start session
$di->setShared('session', function() {
$session = new SessionAdapter();
$session->start();
return $session;
});
//Register custom library Utilities, so that it is available through out the application
$di->setShared("utils",function(){
return new \Utilities();
});
//Registering a router
$di->set('router', function() use ($config){
$router = new Router(false);
$controller = "index";
/*Backend Routers Configuration Start*/
$modules = $config->modules;
$router->add('/', array(
'module' => 'property',
'namespace' => 'RealEstate\Property\Controllers\\',
'controller' => 'index',
'action' => 'index'
));
$router->add('/:int', array(
'module' => 'property',
'namespace' => 'RealEstate\Property\Controllers\\',
'controller' => 'index',
'action' => 'index',
'params' =>1
));
//other router settings
$router->notFound(array(
'module' => 'errors',
'namespace' => 'RealEstate\Errors\Controllers\\',
'controller' => 'index',
'action' => 'show404'
));
$router->removeExtraSlashes(true); //ignore trailing slash in urls
/*Backend Routers Configuration End*/
return $router;
});
$di->set('partials', function() {
$partials = new View();
$partials->setPartialsDir('../apps/common/views/');
return $partials;
});
$this->setDI($di);
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
public function main()
{
try{
if (!extension_loaded('phalcon')) {
die("Phalcon extension is not installed or enabled. Please check with host");
}
$this->_registerServices();
if($this->prConfig->application->environment=="development" || $_GET["showerrors"]==1){
ini_set("display_errors","On");
error_reporting(E_ALL ^ E_NOTICE);
}
$arraytemp = json_decode(json_encode($this->prConfig->modules), true); //convert Config object to a simple array
//$this->utils->printr($arraytemp,1);
$keys = array_keys($arraytemp);
$array = array();
if(count($keys)>0){
foreach($keys as $module){
$array[$module]["className"] = "RealEstate\\".ucwords($module)."\Module";
$array[$module]["path"] = "../apps/modules/".$module."/Module.php";
}
}else{
die("The entries for modules not found.");
}
$this->registerModules($array);
echo $this->handle()->getContent();
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
}
$application = new MyApplication();
$application->main();
Have followed This Link as well, but with not much help.
UPDATE
No errors on Server's error log
Thanks
I think I solved this issue. The issue was in Module.php, the issue was in method
public function registerServices($di)
{
try{
//Registering the view component
$di->set('view', function() {
$view = new View();
$view->setViewsDir('../apps/modules/'.$this->module_name.'/views/');
return $view;
});
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
Where, $module_name is a property defined in class.
In above code $this->module_name was undefined. so I changed above method to -
public function registerServices($di)
{
$module = $this->module_name;
try{
//Registering the view component
$di->set('view', function() use($module) {
$view = new View();
$view->setViewsDir('../apps/modules/'.$module.'/views/');
return $view;
});
}catch(\Phalcon\Exception $e){
echo get_class($e), ": ", $e->getMessage(), "\n";
echo " File=", $e->getFile(), "\n";
echo " Line=", $e->getLine(), "\n";
echo $e->getTraceAsString();
}
}
I wondered why it was working in previous version of Phalcon

Categories