view files are not rendered in zend framework - php

With below code i have set layout and view files path.
class DemoMet_IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$theme = 'metronic_v3';
$layout_name = 'default';
$layout = Zend_Layout::getMvcInstance();
$layoutPath = APPLICATION_PATH . DIRECTORY_SEPARATOR. 'themes'. DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR. 'layouts'. DIRECTORY_SEPARATOR. 'scripts'. DIRECTORY_SEPARATOR;
$layout->setLayoutPath($layoutPath);
$layout->setLayout($layout_name);
$viewPath = APPLICATION_PATH . DIRECTORY_SEPARATOR. 'themes'. DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR. 'views'. DIRECTORY_SEPARATOR;
$layout->getView()->setBasePath($viewPath);
}
}
but when I access the url "http://project.localhost/demoMet/index/" .
Error message
with message 'script 'index/index.phtml' not found in path
project/application/modules/demoMet/views/scripts/
Though the view files path is set but it searching in default script folder

Add a _init function to your main application Bootatrp.php file!
Bootstrap.php
protected function _initViewHelpers() {
//Bootstrap view
$this->bootstrap('view');
//get bootstrapped view
$view = $this->getResource('view');
$view->addScriptPath(APPLICATION_PATH."/templates/default/views/scripts");
//$view->addScriptPath($theme);
$view->addHelperPath(APPLICATION_PATH."/templates/default/views/helpers/", "Administration_View_Helper");
}

Maybe you can try this:
public function indexAction()
{
$theme = 'metronic_v3';
$layout_name = 'default';
// without the last DIRECTORY_SEPARATOR
$layoutPath = APPLICATION_PATH . DIRECTORY_SEPARATOR. 'themes'. DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR. 'layouts'. DIRECTORY_SEPARATOR. 'scripts';
$this->_helper->layout->setLayout($layout_name);
$this->_helper->layout->setLayoutPath($layoutPath);
// with add 'scripts' after the last DIRECTORY_SEPARATOR
$viewPath = APPLICATION_PATH . DIRECTORY_SEPARATOR. 'themes'. DIRECTORY_SEPARATOR . $theme . DIRECTORY_SEPARATOR. 'views'. DIRECTORY_SEPARATOR . 'scripts';
$this->view->setBasePath($viewPath);
}

Related

PHP MVC Class loaded locally but not when uploaded to host

I have created the MVC directory structure and started with writing an "App" class.
Everything works well on the local machine using WAMP. But it fails when uploaded to the hosting server.
So, I compared PHP settings between host and local, all looks good, everything matches version etc. I checked paths etc.
Here is my PRIVATE directory structure:
This is the PUBLIC area
This is the index.php file:
<?php
require_once '../httpd.private/init.php';
require_once '../httpd.private/core/App.php';
$app = new App;
?>
Which loads the INIT.PHP variables:
<?php
// Define path constants
define("DS", DIRECTORY_SEPARATOR);
define("ROOT", getcwd() . DS);
define("APP_PATH", ROOT . '../httpd.private' . DS);
define("VIEW_PATH", ROOT . "views" . DS);
define("MODEL_PATH", APP_PATH . "models" . DS);
define("DATA", APP_PATH . "data" . DS);
define("CORE_PATH", APP_PATH . "core" . DS);
define("CONTROLLER_PATH", APP_PATH . "controllers" . DS);
define('SEC_PATH', APP_PATH . "sec" . DS);
define("UPLOAD_PATH", APP_PATH . "uploads" . DS);
define('FILE_ENCRYPTION_BLOCKS', 10000);
$modules = [ROOT, APP_PATH, VIEW_PATH, MODEL_PATH, DATA, CORE_PATH, CONTROLLER_PATH, SEC_PATH];
set_include_path(get_include_path(). PATH_SEPARATOR . implode(PATH_SEPARATOR,$modules));
spl_autoload_register('spl_autoload', false);
?>
After the init file the App.php kicks in:
<?php
class App
{
protected $controller = 'homeController';
protected $method = 'index';
protected $params = [];
public function __construct()
{
$this->parseUrl();
if (file_exists(CONTROLLER_PATH . $this->controller . '.php'))
{
$this->controller = new $this->controller;
if (method_exists($this->controller, $this->method))
{
call_user_func_array([$this->controller, $this->method], $this->params);
} else {
header("Location: /home/index");
}
} else {
header("Location: /home/index");
}
exit();
}
public function parseUrl()
{
if (isset($_GET['url'])){
$url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
$this->controller = isset($url[0]) ? $url[0] . 'Controller' : 'homeController';
$this->method = isset($url[1]) ? $url[1] :'index';
unset($url[0], $url[1]);
$this->params = !empty($url) ? array_values($url) : [];
}
}
}
?>
The ERROR:
Fatal error: Uncaught Error: Class 'homeController' not found in
/customers/2/e/9/something.com/httpd.private/core/App.php:15
Stack trace: #0 /customers/2/e/9/something.com/httpd.www/index.php(5): App->__construct() #1 {main} thrown in /customers/2/e/9/something.com/httpd.private/core/App.php on line 15
This is line 15 that is mentioned in the error:
$this->controller = new $this->controller;
And here is the controller.php file:
<?php
class Controller
{
protected $view;
protected $model;
public function __construct()
{
/* echo "This is the Class: " . __CLASS__ . "<br>";
echo "And this is the Method: " . __METHOD__ . "<br>";
die(); */
}
public function view($viewName, $data = [])
{
$this->view = new View($viewName, $data);
return $this->view;
}
public function model($modelName, $data = [])
{
if (file_exists(MODEL_PATH . $modelName . 'Model' . '.php')){
require MODEL_PATH . $modelName . 'Model' . '.php';
$this->model = new $modelName;
}
}
}
?>
How can I correct the error and perhaps better improve the code?
I am aware that I could start with using composer and other frameworks, but that will not help my homework.
I don't see any line where you include your controller file.
Before the instantiation of your controller, you need to require the script.
(You have done that with your model)

How to create an object from a class inside another class

I have a problem creating an object from another class inside the constructor of my kernel class, it gives a fatal error which says can not find the class, anybody can help please? I do not know what is wrong?
namespace App\Http;
use App\Http\Config;
use App\Controllers;
class kernel{
protected $controller = "HomeController";
protected $action = "index";
protected $params=[];
public function __construct(){
$url = $this->ParseUrl();
$format_url = ucfirst($url[0]) . "Controller";
if (file_exists(Config::CONTROLLERS_PATH . $format_url . ".php")) {
$this->controller = $format_url;
}
// $path = Config::CONTROLLERS_PATH . $this->controller . ".php";
// echo "path: $path";// path is correct
require_once (Config::CONTROLLERS_PATH . $this->controller . ".php");
// $include_file = get_required_files();
// var_dump($include_file);//require_once is working
//here is the problem
$this->controller = new $this->controller;
}
public function ParseUrl(){
if (isset($_GET['url'])) {
return explode("/", rtrim($_GET['url'], "/"));
}
}
}

PHP - Extend parent class from child class which is in another directory

I try to create a parent class for all my "Model" classes.
I have a class in app/code/core/User/Model/User.php named User_Model_User it should inherit from a parent class in app/code/core/Core/Model.php
Attempt:
Parent:
class Model
{
public function testParent()
{
echo "123";
}
}
Child:
class User_Model_User extends Core\Model
{
private $con;
private $user_id;
public function __construct($con)
{
$this->con = $con;
}
public function loadByEmail($email)
{
$this->user_id = $this->getUserId($email);
return $this;
}
...
Error:
Fatal error: Class 'Core\Model' not found in
/var/www/property-rights/app/code/core/User/Model/User.php
How does it work?
Not sure if this is the best way, but I solved it like this:
Main: app/Main.php
Put <project_root>/app/code/core in include path, so that I don't have to use the full path when calling include, require etc.
if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('PS')) define('PS', PATH_SEPARATOR);
if (!defined('BP')) define('BP', dirname(dirname(__FILE__)));
Main::register('original_include_path', get_include_path());
$paths = array();
$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'core';
$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'local';
$paths[] = BP . DS . 'lib';
$paths[] = BP . DS . 'inc';
$appPath = implode(PS, $paths);
set_include_path($appPath . PS . Main::registry('original_include_path'));
Parent:
namespace Core;
class Model
{
Child:
require_once("Core/Model.php");
class User_Model_User extends Core\Model
{

Load Class in application core's sub-folders in Code Igniter 2

In my application/core directory, I had class MY_Controller.
And now, I want to create two classes in two paths application/core/Frontent/Frontend_Controller.php and application/core/Backend/Backend_Controller.php. Then my modules controllers extend from Frontend_Controller and Backend_Controller class.
But CI always raises class not found error.
Edit March 20th 2014:
I used #manix's suggestion:
1. Write below script at the end of /application/config/config.php
function __autoload($class)
{
if (strpos($class, 'CI_') !== 0)
{
if (file_exists($file = APPPATH . 'core/Frontend/' . $class . EXT))
{
include $file;
}
if (file_exists($file = APPPATH . 'core/Backend/' . $class . EXT))
{
include $file;
}
}
}
Create /application/core/Backend/Backend_Controller.php like this:
(defined('BASEPATH')) OR exit('No direct script access allowed');
class Backend_Controller extends CORE_Controller {
}
I have a Menu class extends Backend_Controller. Then receive this error Fatal error: Class 'Backend_Controller' not found in codeigniter\application\widgets\menu\Controllers\menu.php on line 6. If I put the Backend_Controller.php at /application/core/Backend_Controller.php, it is OK. But I want to put it into a subfolder.
SOLUTION (update March 24th 2014)
Thank to manix. I edited from his code to load classes. Here is the code that works for me.
function __autoload($class) {
if (strpos($class, 'CI_') !== 0) {
if (file_exists($file = APPPATH . 'core/Frontent/' . $class . EXT)) {
include $file;
}
if (file_exists($file = APPPATH . 'core/Backend/' . $class . EXT)) {
include $file;
}
if (file_exists($file = APPPATH . 'core/' . $class . EXT)) {
include $file;
}
}
}
Try to call explicitly the __autoload funtionat the end of the config.php file that raised at application/config/ folder. Look the example above:
function __autoload($class)
{
if (strpos($class, 'CI_') !== 0)
{
if (file_exists($file = APPPATH . 'core/Frontent/' . $class . EXT))
{
include $file;
}
if (file_exists($file = APPPATH . 'core/Backend/' . $class . EXT))
{
include $file;
}
}
}

Allow SVN commit with existing PreCommit hook warnings

I am using SVN precommit hooks to validate my code standard (PSR2) before being able to commit. This works perfectly with just one exception. My unit test (PHPUnit) files exist of my bootstrap class existing of all static unit test functions, but also enables error messages above the bootstrap class definition.
The PSR2 standard will give a warning when trying to commit this, because you cannot have code that is not in a class or function in a file that contains a class definition.
Does anyone have either a way to exclude this error in my codesniffer or a way to make my code valid (without putting the code to enable my error messages in each static function of the bootstrap class)?
Here's the file:
<?php
namespace AlbumTest;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use RuntimeException;
error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
class Bootstrap
{
protected static $serviceManager;
protected static $config;
protected static $bootstrap;
public static function init()
{
// Load the user-defined test configuration file, if it exists; otherwise, load
if (is_readable(__DIR__ . '/TestConfig.php')) {
$testConfig = include __DIR__ . '/TestConfig.php';
} else {
$testConfig = include __DIR__ . '/TestConfig.php.dist';
}
$zf2ModulePaths = array();
if (isset($testConfig['module_listener_options']['module_paths'])) {
$modulePaths = $testConfig['module_listener_options']['module_paths'];
foreach ($modulePaths as $modulePath) {
if (($path = static::findParentPath($modulePath)) ) {
$zf2ModulePaths[] = $path;
}
}
}
$zf2ModulePaths = implode(PATH_SEPARATOR, $zf2ModulePaths) . PATH_SEPARATOR;
$zf2ModulePaths .= getenv('ZF2_MODULES_TEST_PATHS') ?: (defined('ZF2_MODULES_TEST_PATHS')
? ZF2_MODULES_TEST_PATHS : '');
static::initAutoloader();
// use ModuleManager to load this module and it's dependencies
$baseConfig = array(
'module_listener_options' => array(
'module_paths' => explode(PATH_SEPARATOR, $zf2ModulePaths),
),
);
$config = ArrayUtils::merge($baseConfig, $testConfig);
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $config);
$serviceManager->get('ModuleManager')->loadModules();
static::$serviceManager = $serviceManager;
static::$config = $config;
}
public static function getServiceManager()
{
return static::$serviceManager;
}
public static function getConfig()
{
return static::$config;
}
protected static function initAutoloader()
{
$vendorPath = static::findParentPath('vendor');
if (is_readable($vendorPath . '/autoload.php')) {
$loader = include $vendorPath . '/autoload.php';
} else {
$zf2Path = getenv('ZF2_PATH') ?: (defined('ZF2_PATH')
? ZF2_PATH : (is_dir($vendorPath . '/ZF2/library')
? $vendorPath . '/ZF2/library' : false));
if (!$zf2Path) {
throw new RuntimeException(
'Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'
);
}
include $zf2Path . '/Zend/Loader/AutoloaderFactory.php';
}
AutoloaderFactory::factory(
array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true,
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
),
),
)
);
}
protected static function findParentPath($path)
{
$dir = __DIR__;
$previousDir = '.';
while (!is_dir($dir . '/' . $path)) {
$dir = dirname($dir);
if ($previousDir === $dir) {
return false;
}
$previousDir = $dir;
}
return $dir . '/' . $path;
}
}
Bootstrap::init();
How does your precommit-hook look like? Could you just remove the first few lines dynamically before sending the to the Codesniffer?
Another solution would be to set the error_reporting in the init of your bootstrap

Categories