Including a non-class php file via namespace without using relative path -
the problem have been having time including "view" php file resides in location, known class method calling, not place calling it. best explain example:
say have file being included somewhere, responsible rendering table. because there many similar tables in application, use separated file template-like table view , if want change aspects of it, pass needed parameters.
here said concrete view:
[mainview.php] // convert data json. /** @var $model maindatamodel */ $model = maindatamodel::rebuildfromjson($_post["model"]); // prepare data table view /** @var $data tableviewdata */ $data = new tableviewdata(); $data->model = $model; $data->tablebody = "maintablebody.php"; $data->tableclass = "main-table"; $data->viewclass = "main-view"; /** attach table. */ // include("../../common/view/tableview.php"); (1) include("../../../../vendor/composer/wb/common/src/view/tableview.php"); (2)
and here common tableview want pass $data , include page:
[tableview.php] namespace common\controller; use ... /** @var $data tableviewdata */ if (!(isset($data) && $data->checkforrequiredfields($data))) { return; } ?> <div class="<?php echo $data->viewclass; ?>"> <div class="datatable"> <table class="<?php echo $data->tableclass; ?>"> <thead> <tr> <?php /** @var $column columnmodel */ foreach ($data->model->columns $column): ?> <th><?php echo $column->text ?></th> <?php endforeach; ?> </tr> </thead> <tbody class="datatable-body"> <?php include($data->tablebody); ?> </tbody> </table> </div> </div>
all fine (relatively) long use include (1), when switched composer separated common classes , put them in remote location, should not care about.
in other words, tells me shouldn't need have knowledge exact path tableview.php, relative wherever using , there has better way use it. obviously, (2) doesn't quite work , surprised if such foolish way have worked.
so question is: how include view (tableview) without using relative path every time use it? along lines of including , accessing controller class (tableviewcontroller?), in same directory tableview , holds information absolute positioning of tableview?
some way around problem make class return view , call class namespace, that's workaround, not solution.
after playing around various path functions , constants i've come solution of problem. it's not neat nevertheless works. here is:
[tableviewcontroller.php] (...) public static function gettableviewpath() { return __dir__ . directory_separator . ".." . directory_separator . "view" . directory_separator . "tableview.php"; } (...) [mainview.php] (...) /** attach table. */ include(tableviewpresenter::gettableviewpath()); (...)
Comments
Post a Comment