how to use the namespace classes in php - php

I have a class with namespace which require many other classes further . main class is
<?php
/**
* Deals with PDF document level aspects.
*/
namespace Aspose\Cloud\Pdf;
use Aspose\Cloud\Common\AsposeApp;
use Aspose\Cloud\Common\Product;
use Aspose\Cloud\Common\Utils;
use Aspose\Cloud\Event\SplitPageEvent;
use Aspose\Cloud\Exception\AsposeCloudException as Exception;
use Aspose\Cloud\Storage\Folder;
class Document
{
public $fileName = '';
public function __construct($fileName='')
{
$this->fileName = $fileName;
}
/**
* Gets the page count of the specified PDF document.
*
* #return integer
*/
public function getFormFields()
{
//build URI
$strURI = Product::$baseProductUri . '/pdf/' . $this->getFileName() . '/fields';
//sign URI
$signedURI = Utils::sign($strURI);
//get response stream
$responseStream = Utils::ProcessCommand($signedURI, 'GET', '');
$json = json_decode($responseStream);
return $json->Fields->List;
}
}
I am using this like this in index.php
<?
ini_set('display_errors', '1');
use Aspose\Cloud\Pdf;
$document=new Document;
echo $document->GetFormFields();
//or like this
echo Document::GetFormFields();
//also tried this
echo pdf::GetFormFields();
?>
Error
Fatal error: Class 'Document' not found in /var/www/pdfparser/asposetry/index.php on line 5
Document class path is Aspose/Cloud/Pdf/Document.php
attempt one
working if i use to include in index.php include(Aspose/Cloud/Pdf/Document.php) but then further namespace produce error. Very difficult to change every use namespace with include. can anybudy tell me the solution for this ??
thanks.

namespace Aspose\Cloud\Pdf;
class Document {
...
To use this class, you'll have to write
use Aspose\Cloud\Pdf\Document
You can also access it without a use statement, but then you'll have to write the full name every time:
$document=new Aspose\Cloud\Pdf\Document;
// Or if you're in a namespace, you'll have to do this:
$document=new \Aspose\Cloud\Pdf\Document;

You are trying to use the Document class that's inside the Aspose\Cloud\Pdf namespace, but you are actually using a Document class without a namespace. You have to use one of the following ways:
//Option one:
use Aspose\Cloud\Pdf\Document;
Document::getFormFields();
//Option two:
Aspose\Cloud\Pdf\Document::getFormFields();
Also note that you can't use Document::getFormFields() as a static function, because it is not static. You should make it static (by putting static between public and function) or use it on an object.

Related

PHP Overload class by other with the same name and namespace

I have a directory tree where in different sub-directories I have a lot of classes with the same name. There is a strong intention to not edit these classes.
I'm looking for a way to load one class and after using it and destroying its instance load another with exactly the same name. Then use it, destroy its instance and repeat that process.
I thought some possible solutions:
Loading class with the same name that replaces previously loaded class (Overloads it)
Unloading a class before I load class with the same name but from different path
Creating a new class (dynamically created class body) under different name or by adding to it namespace. Creation process firstly reads source class body, its methods, properties and "copies" that to new class. Similar to clone on instances but done on class body level.
Read the first class, instantiate it, use its methods, destroy its instance. Then remove all methods inside first class and dynamically create inside it all methods that are read from the second class having the same name.
Read file content of a class and create temporary file with the class content you read but change class name or put unique namespace on top of it and finally load temporary file. (Least appealing approach to me)
For the 3rd I thought this could be useful: Componere or Runkit or Classkit but don't have any experience with them.
Do you have any other ideas or perhaps some solutions?
Did you use componere or Runkit / Classkit and can say they suit the job? maybe there are other options?
Perhaps there is a OOP design pattern that covers this issue but I'm not familiar with it.
Example code:
<?php
#------------------------------------
//path Foo/Bar.php
/* class is without a namespace or have the same
as Baz/Bar.php */
class Bar
{
public function getName() : string
{
return 'Foo/Bar';
}
}
#------------------------------------
//path Baz/Bar.php
/* class is without a namespace or have the same
as Foo/Bar.php */
class Bar
{
public function getName() : string
{
return 'Baz/Bar';
}
}
#------------------------------------
//path ./Execute.php
$paths = [
'Foo/Bar.php',
'Baz/Bar.php'
];
$results = [];
foreach ($paths as $path) {
//how to create instance of class Bar in Foo/Bar.php and then in Baz/Bar.php
//without PHP Fatal error: Cannot declare class...
$classDynamic = ...
$results[] = $classDynamic->getName();
unset($classDynamic);
}
var_export($results)
/**
* prints
* array('Foo/Bar', 'Baz/Bar')
*/
I do not think there is a way to unset a class once it has been defined and as they share the same namespace they will error out.
but you could get the effect you wanted as follows
class Bar
{
$myname = "";
function __construct($setname="")
{
$this->myname = $setname;
}
function getName()
{
return $myname;
}
}
$paths = array('Foo/Bar','Baz/Bar');
$results = array();
foreach($paths as $p)
{
$bit = new Bar($p);
$results[] = $bit->getName();
}
var_export($results);

PHP namespace Error (the name is already in use)

I'm trying to run this code on the same file:
namespace Foo1\Bar\SubBar;
class SubBarClass {
public function __construct() {
echo 'From Foo1';
}
}
namespace Foo2\Bar\SubBar;
class SubBarClass {
public function __construct() {
echo 'From Foo2';
}
}
use Foo1\Bar\SubBar;
$foo1 = new SubBarClass;
use Foo2\Bar\SubBar;
$foo2 = new SubBarClass;
The ideia is to change namespaces and echo the related value.
But it's returning the following error:
( ! ) Fatal error: Cannot use Foo2\Bar\SubBar as SubBar because the name is already in use in C:\wamp\www\xxx\namespaces.php on line 30
Line 30: use Foo2\Bar\SubBar;
How can I interchange namespaces on the same file?
Thks!
use keyword is used to import that namespace to be accessed in your current file scope. It does not act as a namespace "instance constructor".
You're current under Foo2\Bar\SubBar namespace. Like a directory of classes, while you're here, you should access other namespaces from the root (\):
$foo2 = new SubBarClass;
$foo1 = new \Foo1\Bar\SubBar\SubBarClass;
There is no need to use use for those namespaces (although you can, specially when they share parent namespaces), they are already declared in the same file you're using them.
For more information about this, consider reading the manual, where it describes using multiple namespaces in the same file.
This happens because the last defined namespace is the one currently active.
So, when I type:
use Foo1\Bar\SubBar;
I'm still on the last defined namespace: Foo2\Bar\SubBar.
Hence, when I type:
use Foo2\Bar\SubBar;
I'm trying to use the currently active namespace. That's why the Fatal error is returned.
On possible solution is:
namespace Foo1\Bar\SubBar;
class SubBarClass {
public function __construct() {
echo 'From Foo1';
}
}
namespace Foo2\Bar\SubBar;
class SubBarClass {
public function __construct() {
echo 'From Foo2';
}
}
use Foo1\Bar\SubBar;
$foo1 = new SubBar\SubBarClass;
echo '<br>';
$foo2 = new SubBarClass;
Cheers!

Laravel 5.1 - How to use Model in Global function file

I created a common.php for my all the global function. When I run my first function {{Common::test()}}
It's working fine But I can not use model in it.
namespace App\library;
{
class Common {
public static function test()
{
echo "Yes";
return "This comes from Common File";
}
public static function getCmsBlocks()
{
$model = Modelname::all();
if($model){
echo "asdad";
}else
{
echo "sadasd";
}
}
}
}
I don't get my output when I run {{Common::getCmsBlocks()}}
If your model is in different namespace than App\library you will need to prefix the model class name with its namespace, otherwise PHP will try to load App\library\Modelname which might not be what you need.
Replace
$model = Modelname::all();
with
$model = \Your\Model\Namespace\Modelname::all();
If you use your Modelname class in multiple place in declared namespace, you can import/alias that using use statement so that you can refer to that class by classname in your code:
namespace App\library;
use Your\Model\Namespace\Modelname;
{
class Common {
public static function getCmsBlocks()
{
$model = Modelname::all(); //this will work now
}
}
}
There is no way to define global use to bused by all namespaces in your file, as use always refers to the namespace being declared.
As above the answer is perfect but just a few addition if you don't want to include namespace everytime on at start of each file
Use this :
\App\ModelName::all();
\App\ModelName1::update(item);
\App\ModelName2::find(1);
give path like above and there will be no need to use namespace everytime .
Note: above is path to model which is inside App directory . So change accordingly if you are keeping them at separate place .

How can I avoid two Class with same name?

In my php file i am doing it this way
pagecontroller.php
include_once(RUDRA."/controller/AbstractTemplateController.php");
if (file_exists(get_include_path() . CONTROLLER_PATH . "/TemplateController.php" )) {
include_once (CONTROLLER_PATH . "/TemplateController.php");
} else {
include_once (RUDRA . "/controller/TemplateController.php");
}
in TemplateController.php a class named 'TemplateController extends AbstractTemplateController' is defined, if a developer has already defined a class TemplateController which also extends AbstractTemplateController then it will use that otherwise it will fallback to default definition.
then in other files i will simply use something like this
include_once("pagecontroller.php")
$c = new TemplateController();
is there any better way to do this?
since I am including two files AbstractTemplateController.php & TemplateController.php in both cases, I cpuld have written both class definitions in same file which would have saved one include(if there is no custom TemplateController.php)?
I tried writing AbstractTemplateController & TemplateController in one single file but if then developer has defined his own TemplateController it creates two classes with same name situation.
pupose is to have atleast one definition to be there, if customDefinition does not exists then only use default one. and this code is to be abstract.
in the beginning if CustomClass exists (in a specific folder) then that the definition to be used, else use default one (which is nothing but simply extends AbstractOne)
CONTROLLER_PATH . "/TemplateController.php"
class TemplateController extends AbstractTemplateController {
/* over-ridden method of AbstractTemplateController
*/
public function invoke($abc,$def){
echo $abc . " " .$def;
}
}
RUDRA . "/controller/TemplateController.php"
class TemplateController extends AbstractTemplateController {
// nothing at all this is simply to make sure TemplateController class is available
// for others to use.
}
Use namespaces and convention.
E.g. you could check if there's a TemplateController-class present that extends the AbstractTemplateController that's different from your namespace (As your implementation will be specific for your namespace), if there isn't ; fall back to your implementation of the TemplateController.
http://php.net/manual/en/language.namespaces.php
php provides a function for not letting you load/write a class more then once.
bool class_exists ( string $class_name );
example is :
<?php
function __autoload($class)
{
include($crigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}lass . '.php');
// Check to see whether the include declared the class
if (!class_exists($class, false)) {
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
in above example autoload is used, you could do it without autoload this way :
<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
still i am saying you better get habit of using namespaces. they are awesome and work every where.

php5 and namespace?

I work a lot in PHP but I never really understand the namespace method in PHP. Can somebody help me here? I have read on php.net's website its not explained good enough, and I can't find examples on it.
I need to know how I can make code in sample version.
namespace: sample
class: sample_class_1
function: test_func_1
class: sample_class_2
function: test_func_2
function: test_func_3
Like this?
<?php
namespace sample
{
class Sample_class_1
{
public function test_func_1($text)
{
echo $text;
}
}
class Sample_class_2
{
public static function test_func_2()
{
$c = new Sample_class_1();
$c->test_func_1("func 2<br />");
}
public static function test_func_3()
{
$c = new Sample_class_1();
$c->test_func_1("func 3<br />");
}
}
}
// Now entering the root namespace...
// (You only need to do this if you've already used a different
// namespace in the same file)
namespace
{
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();
}
// Now entering yet another namespace
namespace sample2
{
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();
}
If you're in another file you don't need to call namespace { to enter the root namespace. So imagine the code below is another file "ns2.php" while the original code was in "ns1.php":
// Include the other file
include("ns1.php");
// No "namespace" directive was used, so we're in the root namespace.
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();

Categories