Similar function like getScriptPath from ZF1 in ZF2 - zend-framework2

I'm currently mapping my ZF1 applications to ZF2 and was wondering if there is a similar function like $this->view->getScriptPath() from ZF1 in ZF2? I spend already my half day, but didn't find a good solution. It would also be fine to get at least the basePath of the Module or the template folder of the Module.

Based on the follow-up questions, what you are really looking for is the path to a given template file. This is actually relatively easy, assuming you're using the default PhpRenderer: you grab the resolver, and resolve the path.
If you're inside a view script already, the following should work:
$path = $this->resolver($templateName);
If you're elsewhere, you need access to either the PhpRenderer, or the ViewResolver. If you have access to the service manager, pull the ViewResolver service, and call resolve() on it:
$resolver = $services->get('ViewResolver');
$path = $resolver->resolve($templateName);
This is superior to knowing where the module lives, as the developer may have chosen to override the template within the application; the resolver will know where even the new location is.

Related

Dropwizard: customize health check address and format

Is it possible to customize Dropwizrd's healthcheck output so that, e.g.: /health for healthchecks instead of /healthcheck and some output like {“status”: 200}.
I realise I could simply write a new resource that does what ever I need, I was just wondering if there is a more standard way to do this.
From what I have read on the 0.7.1 source code it's not possible to change the resource URI for healthchecks unfortunately, I highly doubt you can change the healthcheck format. I also remember people complaining about not being able to add REST resources to admin page, only servlets. Maybe on 0.8.0?
Here are the details of what I've tracked so far on the source code. Maybe I have misread or misunderstood something, so somebody could fix it.
Metrics has actually written AdminServlet to add healtcheck servlet in a way that it checks the servlet config whether the URI is defined or not.
this.healthcheckUri = getParam(config.getInitParameter(HEALTHCHECK_URI_PARAM_KEY), DEFAULT_HEALTHCHECK_URI);
But dropwizard doesn't provide a way to inject this configuration in any way on AbstractServerFactory.
handler.addServlet(new NonblockingServletHolder(new AdminServlet()), "/*");
NonblockingServletHolder is the one which is providing the config to AdminServlet but is created by AbstractServerFactory with empty constructor and provides no way to change the config.
I've thought of and tried to access the ServletHolder from the Environment object on Application.run method but the admin servlets are not created until after run method is run.
environment.getAdminContext().getServletHandler().getServlets()[0].setInitParameter("healthcheck-uri", "/health");
Something like this in your run() function will help you control the URI of your healthchecks:
environment.servlets().addServlet(
"HealthCheckServlet",
new HealthCheckServlet(environment.healthChecks())
).addMapping("/health");
If you want to actually control what's returned you need to write your own resource file. Fetch all the healthchecks from the registery, run them and return whatever aggregated value you want based on their results.

Including an external application in ZF2

I'm trying to use phpBB3 (forum app) along with ZF2. For that, I have to include a file from the phpBB3. In theory this is as simple as:
include('/path/to/phpbb3/common.php');
$user->session_begin(); //$user is defined in common.php file
In common.php a lot of globals are defined, and after that are required some files which are using those globals.
In ZF2 simply including the common.php would not work, because the scope of the globals will not span over the required files, so I tried a little trick:
//in Application/Forum/Service
public function callForumAPI(){
$zf_dir = getcwd();
chdir('/var/www/html/phpBB3');
include('common.php');
$user->session_begin();
chdir($zf_dir);
}
Neither in this case the scope of the global variables didn't span over the required files, so all the globals where NULL in those files.
How could I solve this issue?
I consider 2 main problems:
1. Loading resources
I dont know if you changed the code of phpBB3, since if you dont, your problem is other.
Phpbb3, as many systems, doesnt let you access directly to any file, you have to go through index.php. As you can see in common.php
if (!defined('IN_PHPBB'))
{
exit;
}
IN_PHPBB is defined in index.php, so you can simply use
Also, common.php and other files, makes use of $phpbb_root_path, that is defined in index.php.
So, at least, when you are going to include common.php you need
$zf_dir = getcwd();
chdir('/var/www/html/phpBB3');
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
include('common.php');
...
chdir($zf_dir);
probably there are some other things you have to take care about.
2. Variable scopes
Also, consider than in PHP, like in almost every language, a variable declared inside a function, is considered local, and will be undefined outside that function. So for sure, if you do that inside callForumAPI(), you wont have any variable outside, and moreover, depending on where you are doing that includes...it could be actually inside a function, no matter you can notice it or not, since ZF2 is a framenwork with a complex, non-obvius architecture.
So, what i recomend, as soon as you load the file, is to use the ZF2 service manager to store all the variables and object than you would use in your application. This is a good measure even if you didnt need it,since this way you can have everything integrated as much as possible, it is important to minimize and localize access to phpbb3, since it is not meant to be a library, maintenance could be tricky, so if everyhing is in the same file, and then you create your own internal api through the service manager, it will more encapsulated and nicer. I assume you already know how to do this, if you dont, just let me know.
try this, and tell me if its enough or we need more research

How can i load config file but not autoload in zf2

I have some config file,they don't need use in everywhere,so i don't want it autoload,can you tell me how to load config file in controller and it can be get in serviceLocator,don't tell me to use zend\config\config, thanks。
First off, it's not advised to ask a question and then directly say that you don't want someone to tell you about XY. What if XY would be the only way?
You could always do something like
$onlyNowConfig = require_once('./config/onlyNowConfig.php');
The current working directory of PHP is the root of your application, as it's set in your public/index.php via the chdir() function.
Other than that, there's no real harm to include the configuration inside your module.config.php. The ModuleManager will check for the existance of the getConfig() function inside your Module class. If it's existant, the Configuration will be loaded. Typically every module has a config that will be loaded. And there's no real speed (dis)advantage of outsourcing 100-200 configuration lines into a separate file. The additional I/O you'd do by only including it on those few actions you need it would actually be higher than the very little time it takes longer to merge the configuration (probably like 1ms total vs. 2-3ms I/O).
I'd advise to just include it in your module.config.php and you'd have it available everywhere via the ServiceLocator, otherwise just include/require the one config file that you need, wherever you are. The include/require parameter would never change, as the working directory of PHP will not change, no matter in what file you are (as long as you don't set it anew via chdir() - which would be highly not recommended).

ZF2 Directory/Namespace Model Object Location

In the zf2 database and models tutorial a path such as this leads to a directory containing my model classes:
module/Album/src/Album/Model
I have created two more classes at:
module/Album/src/Album/Model/AlbumRelatedClass.php
module/Album/src/Album/Model/AlbumRelatedTable.php
I would like to put these classes at
module/Album/src/AlbumRelated/Model/
I have created duplicates of the model classes there for the purposes of this test, unfortunately, my module config for Album tells me that it cannot find the classes at the AlbumRelated location. I have tried changing the namespaces in the AlbumRelated location to AlbumRelated\Model and directly referring to the class location (\Album\Model\AlbumRelated()) without success.
Does anyone know how I can do this? If I shouldn't be doing this, can somebody explain why? I'm also interested to know why the folder structure is Album/Model/Album (it seems redundant, and I wasn't clear on the explanation in the tutorial).
Any help given would be great, thanks :)
The short answer is that it can't find the class because you probably didn't set up the autoloader config to know about a new "AlbumRelated" namespace. Look at what happens in \Album\Module::getAutoloaderConfig(). You probably want to add a key/value pair to namespaces like 'AlbumRelated' => __DIR__ . '/src/AlbumRelated'. That will tell the autoloader where to look for classes under the AlbumRelated namespace.
That said,
If I shouldn't be doing this, can somebody explain why?
You probably shouldn't be doing it that way. You've got a top-level namespace called \Album. Then you have \Album\Model namespace under it. Any models related to Albums ought to live there. Imagine you had an entity in your system for Record Labels, so you could associate an Album with the label that released it. The ZF2 expectation is that you'd create a class called \Album\Model\RecordLabel that lived in module/Album/src/Album/Model/RecordLabel.php. As long as we assume that RecordLabels are primarily related to albums, that all makes perfect sense.
Of course, you could stick RecordLabel in it's own module as well, if you had a lot of workflow around managing them.
I'm also interested to know why the folder structure is Album/Model/Album
I assume you mean Album/src/Album. That redundancy is to keep a nice clean PSR-0 setup. So, the first Album is identifying the module, and the second is the top-level of the Album namespace. This provides maximum flexibility, but isn't a hard and fast rule. See Rob Allen's recent blog post about alternative module layouts in zf2 for an exploration.

Translating server file paths to URLs in Codeigniter

I'm developing my first application in Codeigniter 2.0.2, and I've got a minor issue I can't seem to find any info about on the web.
The application revolves around resources stored locally on the server (namely images and audio files) which need to be exposed to the user. The locations of these resources are stored in a DB as absolute paths. As a result, I find myself needing to translate server paths to base_url-based URLs fairly often.
I already wrote a simple and robust-enough function to handle it for me, but with all the seemingly-relevant helpers in CI (url, path), I can't shake the feeling that I just reinvented the wheel.
At the least, I would think there would be some kind of CI function (say, "basify") that will translate any server path to a base_url-relative path like so:
$server_path = '/server/path/to/app/resources/image.jpg';
basify( $server_path ); // returns 'resources/image.jpg' or './resources/image.jpg'
where the CI app lives in /server/path/to/app. Then it's a simple call to base_url() to make the URL.
Does anything like that exist?
Edit: And yes, I know that a simple preg_replace will handle most cases for me (at least those where the resource is within the base path), but I feel like this should be CI's job, not mine! Half the reason I'm using it is because I don't want to think about path management.
Maybe you can use php function str_replace together with codeigniter FCPATH constant.
Your code will be:
function basify($image_path) {
return str_replace(FCPATH, '', $image_path);
}
The FCPATH constant is new to me, but I have done some tests and it works fine.

Resources