PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label namespaces. Show all posts
Showing posts with label namespaces. Show all posts

Monday, December 19, 2022

[FIXED] What does __all__ mean in Python?

 December 19, 2022     namespaces, python, syntax     No comments   

Issue

I see __all__ in __init__.py files. What does it do?


Solution

It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.



Answered By - Jimmy
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 25, 2022

[FIXED] How to tell if Python module is a namespace module

 November 25, 2022     module, namespaces, python, python-3.x     No comments   

Issue

In Python 3, modules can be namespace modules without an __init__.py (as per PEP 420) or as a regular module (i.e. '[modules] packages as they are implemented in Python 3.2 and earlier' - PEP 420) that have an __init__.py or are a single .py file.

How can you tell the difference between a namespace module and an 'ordinary' module?

(I am using Python 3.5.3)

e.g. Namespace module named mod prints out as:

(Pdb) mod
<module 'mymodule' (namespace)>

and ordinary modules print out as:

(Pdb) mod
<module 'mymodule' from '/path/to/mymodule/__init__.py'>

Solution

Namespace packages have a __path__, and either __file__ set to None or no __file__ attribute. (__file__ is set to None on Python 3.7 and later; previously, it was unset.)

if hasattr(mod, '__path__') and getattr(mod, '__file__', None) is None:
    print("It's a namespace package.")

In contrast, modules that aren't packages don't have a __path__, and packages that aren't namespace packages have __file__ set to the location of their __init__.py.



Answered By - user2357112
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] How can I change the application name(space) in Laravel 6

 November 15, 2022     laravel-6, laravel-artisan, namespaces, php     No comments   

Issue

In previous versions you could use the artisan command

php artisan app:name NewName

to use change the applications namespace (defaults to App). The artisan command seems to be missing now. Is changing the namespace no longer supported?


Solution

Unfortunatelly, the command has been officially removed from Laravel version 6 (see pull request: https://github.com/laravel/framework/pull/27575).

https://github.com/laravel/framework/issues/29810



Answered By - Simon
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] What if an argument has the same name as that of a data member?

 October 20, 2022     c++, class, datamember, namespaces, standards     No comments   

Issue

#include <iostream>

struct A
{
    A(int n) { std::cout << n; }
    int n{2};
};

int main()
{
    A a{1};
}

The output is 1 rather than 2.

Does the C++ standard define that the argument name is preferred if it is the same as that of a data member?


Solution

The argument is in a "closer" scope than the member variable, so the argument shadows the member variable.

The obvious solution is to rename the argument (or the member variable), so they are not the same anymore.

You can also use this->n to explicitly use the member variable.



Answered By - Some programmer dude
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 25, 2022

[FIXED] How to divide a script in a smaller script and a module and connect to workspace variable?

 August 25, 2022     module, namespaces, python     No comments   

Issue

I start up sessions in Jupyter with Python with a partly tailor-made script for the application I work with. The script contains both application dependent dictionaries and functions, but some function are of a general kind. I would like to make a general module and make the start-up script contain only application parts. The difficulty is that I want the functions in the general module have application dictionaries as default. So how to connect such workspace dictionaries to the imported functions?

A very simplifed example below illustrate the problem. First you see the original total startup script. This codes works.

import numpy as np
import matplotlib.pyplot as plt

parDict = {}
parDict['Y'] = 0.5
parDict['qSmax'] = 1.0
parDict['Ks'] = 0.1

def par(parDict=parDict, *x, **x_kwarg):
   """ Set parameter values if available in the predefined dictionaryt parDict. """
   x_kwarg.update(*x)
   x_temp = {}
   for key in x_kwarg.keys():
      if key in parDict.keys():
         x_temp.update({key: x_kwarg[key]})
      else:
         print(key, 'seems not an accessible parameter')
   parDict.update(x_temp)

And I can in the notebook give a command like par(Y=0.4) and then inspect the results in the dictionary parDict.

Second (below) you see an attempt to break out the general functions into a module and this functions are imported in the start-up script. And below the actual module. This code does not work. The error message is: name 'parDict' is not defined How to fix it?

parDict = {}
parDict['Y'] = 0.5
parDict['qSmax'] = 1.0
parDict['Ks'] = 0.1

from test_module import par

And test_module.py

def par(parDict=parDict, *x, **x_kwarg):
   """ Set parameter values if available in the predefined dictionaryt parDict. """
   x_kwarg.update(*x)
   x_temp = {}
   for key in x_kwarg.keys():
      if key in parDict.keys():
         x_temp.update({key: x_kwarg[key]})
      else:
         print(key, 'seems not an accessible parameter')
   parDict.update(x_temp)

If I in the function take away the default argument parDict then it works, but I must then have a lengthier call like par(parDict, Y=0.4). I would like avoid this lengthy call and provide the default parDict automatically. One idea is to in the start-up script make a new function from the imported function and here make the connection to the dictionary. But seems a clumsy way to do it, or the only choice?


Solution

Now I have put together an even better solution that I want to share with you! The key is to make use of Python class-concept that give the possibility to combine a dictionary with associated functionality and you import the class from a module. In the setup-file you then after import of the class populate the dictionary with application parameter names and value and you make a short name for the associated function. This could be described in terms of "abstract datatype" if you like.

The start-up script now look like this:

from test_module3 import ParDict

p = {}
p['Y'] = 0.5
p['qSmax'] = 1.0
p['Ks'] = 0.1

parDict = ParDict('Test3', p)

par = parDict.parX

and the updated test_module3 is now somewhat more complex:

class ParDict(object):
   """"Tool to associate a dictionary parDict with robustified way to   
       modifiy parameter values."""
          
   def __str__(self):
      return self.id

   def __init__(self, id, parDict):
      self.id = id 
      self.parDict = parDict
  
   def parX(self, *x, **x_kwarg):
      x_kwarg.update(*x)
      x_temp = {}
      for key in x_kwarg.keys():
         if key in self.parDict.keys():
            x_temp.update({key: x_kwarg[key]})
         else:
            print(key, 'seems not an accessible parameter')
      self.parDict.update(x_temp)
  

Finally out in the Jupyter notebook you can now change parmeter values in parDict as before with simplified command-line par(Y=0.4, Ks=0.08) etc.



Answered By - janpeter
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 24, 2022

[FIXED] Why is a function from a Julia submodule being shadowed?

 August 24, 2022     julia, module, namespaces, shadowing     No comments   

Issue

Consider the following code:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

When I run this, if I try calling g() I get "abc" as expected. If I call h() I get an error message. Somehow, the definition of f(::Int) is being shadowed. Is that supposed to happen? How to fix this?

If I omit the definition of f(::String) then h() works.


Solution

Yes, this is correct behaviour. In order to extend method it should be imported (https://docs.julialang.org/en/v1/manual/modules/#using-and-import-with-specific-identifiers,-and-adding-methods)

So, correct example should look like this:

module Foo
export g, h

  module Bar
  export f

  f(::Int) = 2

  end

using .Bar
import .Bar: f

f(::String) = "abc"

g() = f("a")
h() = f(12)

end

I've added import .Bar: f because Bar can export other names, which you do not want to extend. So it is fine to mix these two together. With this addition, everything is working as intended

julia> using .Foo

julia> g()
"abc"

julia> h()
2


Answered By - Andrej Oskin
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, July 22, 2022

[FIXED] How to import static function with namespace in php?

 July 22, 2022     namespaces, php, php-5.4, php-5.5     No comments   

Issue

class A declared at namespace1.

namesapce namesapce1;
class A
{
  public static function fun1()
  {
  }

}

I want to use fun1() inside class B:

namespace namesapce2;
use ???? as fun1
class B
{
    public static func2()
    {
          fun1();
    }
}

How to do that ?


Solution

namespace namespace2;

use namespace1\A;

class B
{
    public static function func2()
    {
          A::fun1();
    }
}

Assuming you're using something that does autoloading or the necessary includes.



Answered By - ChadSikorra
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to import static function with namespace in php?

 July 22, 2022     namespaces, php, php-5.4, php-5.5     No comments   

Issue

class A declared at namespace1.

namesapce namesapce1;
class A
{
  public static function fun1()
  {
  }

}

I want to use fun1() inside class B:

namespace namesapce2;
use ???? as fun1
class B
{
    public static func2()
    {
          fun1();
    }
}

How to do that ?


Solution

namespace namespace2;

use namespace1\A;

class B
{
    public static function func2()
    {
          A::fun1();
    }
}

Assuming you're using something that does autoloading or the necessary includes.



Answered By - ChadSikorra
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] How do I get an object's unqualified (short) class name?

 July 07, 2022     class, namespaces, php     No comments   

Issue

How do I check the class of an object within the PHP name spaced environment without specifying the full namespaced class.

For example suppose I had an object library/Entity/Contract/Name.

The following code does not work as get_class returns the full namespaced class.

If(get_class($object) == 'Name') {
... do this ...
}

The namespace magic keyword returns the current namespace, which is no use if the tested object has another namespace.

I could simply specify the full classname with namespaces, but this seems to lock in the structure of the code. Also not of much use if I wanted to change the namespace dynamically.

Can anyone think of an efficient way to do this. I guess one option is regex.


Solution

You can do this with reflection. Specifically, you can use the ReflectionClass::getShortName method, which gets the name of the class without its namespace.

First, you need to build a ReflectionClass instance, and then call the getShortName method of that instance:

$reflect = new ReflectionClass($object);
if ($reflect->getShortName() === 'Name') {
    // do this
}

However, I can't imagine many circumstances where this would be desirable. If you want to require that the object is a member of a certain class, the way to test it is with instanceof. If you want a more flexible way to signal certain constraints, the way to do that is to write an interface and require that the code implement that interface. Again, the correct way to do this is with instanceof. (You can do it with ReflectionClass, but it would have much worse performance.)



Answered By - lonesomeday
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, June 26, 2022

[FIXED] how to solve: error: global qualification of class name is invalid before '{' token

 June 26, 2022     c++, compiler-errors, gcc, namespaces     No comments   

Issue

I'm trying to build https://android.googlesource.com/device/generic/vulkan-cereal but have run into an error that seems to only happen with GCC (v8.3 is what I have to work with).

There are related questions, but I still don't understand what's going on well enough to fix the issue:

  • Global qualification in base specifier
  • Global qualification in a class declarations class-head

The code:

https://android.googlesource.com/device/generic/vulkan-cereal/+/refs/heads/master/stream-servers/vulkan/vk_fn_info.h

#define REGISTER_VK_FN_INFO(coreName, allNames)                 \
    struct coreName;                                            \
    template <>                                                 \
    struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {       \
        static constexpr auto names = std::make_tuple allNames; \
        using type = PFN_vk##coreName;                          \
    };

REGISTER_VK_FN_INFO(GetPhysicalDeviceProperties2,
                    ("vkGetPhysicalDeviceProperties2KHR", "vkGetPhysicalDeviceProperties2"))

The Error:

vulkan-cereal/stream-servers/vulkan/vk_fn_info.h:31:57: error: global qualification of class name is invalid before '{' token
     struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {       \
                                                         ^

/vulkan-cereal/stream-servers/vulkan/vk_fn_info.h:36:1: note: in expansion of macro 'REGISTER_VK_FN_INFO'
 REGISTER_VK_FN_INFO(GetPhysicalDeviceProperties2,
 ^~~~~~~~~~~~~~~~~~~

What can I do to get this to build?


Solution

The global qualifier is the two colons at the front:

struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {
       ^^

But the answer was to remove all qualifiers:

struct ::vk_util::vk_fn_info::GetVkFnInfo<coreName> {
       ^^^^^^^^^^^^^^^^^^^^^^^

So it becomes:

#define REGISTER_VK_FN_INFO(coreName, allNames)                 \
    struct coreName;                                            \
    template <>                                                 \
    struct GetVkFnInfo<coreName> {                              \
        static constexpr auto names = std::make_tuple allNames; \
        using type = PFN_vk##coreName;                          \
    };

The trick was that this revealed knock-on errors caused by the macro being improperly used outside the namespaces in another file:

vk_util_unittest.cpp:28:25: error: expected constructor, destructor, or type conversion before '(' token
 REGISTER_VK_FN_INFO_TEST(GfxstreamTestFunc, ("vkGfxstreamTestFunc", "vkGfxstreamTestFuncGOOGLE",

The final change required fixing the namespaces in vk_util_unittest.cpp so that they matched the ones in vk_fn_info.h

As an alternative, I found that the macro could be used outside the namespace as long as it was fully qualified (excluding the invalid global qualification):

#define REGISTER_VK_FN_INFO_EXTERN(coreName, allNames)          \
    struct coreName;                                            \
    template <>                                                 \
    struct vk_util::vk_fn_info::GetVkFnInfo<coreName> {         \
        static constexpr auto names = std::make_tuple allNames; \
        using type = PFN_vk##coreName;                          \
    };

But this prevented it from being used within the namespace. Two separate macros would be needed to satisfy use within and without the namespace.



Answered By - jpx
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 9, 2022

[FIXED] Yii2: Stand alone Action in Module

 March 09, 2022     action, namespaces, php, yii, yii2     No comments   

Issue

I want to create a directory tree like this:

  • models
  • modules
    • help
      • controllers
        • default
          • IndexAction.php
        • DefaultController.php
      • views
        • default
          • index.php
      • help.php

So that if I call localhost/mysite/web/index.php?r=help/default/index I should get the index view.

So I created a module withe gii. My Module Class is "app\modules\help\help". I had to use help twice so that I get my module in a subdirectory. ( This is something I don't get. Why doesn't create Yii an subdirectory for each module?)

In the next step I created my Stand Alone Action

<?php
namespace app\modules\help\controllers;

use yii\base\Action;

class IndexAction extends Action
{

    public function run()
    {
        $this->controller->render('index');
    }

}

In the next step I modified my Controller to use the stand alone action

<?php

namespace app\modules\help\controllers;

use yii\web\Controller;

class DefaultController extends Controller
{

    public function actions()
    {
        return [
            'index'    => 'app\modules\help\controllers\default\IndexAction',
        ];
    }

}

If I call now my view in the browser I get the following error:

Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?

But if I go to this Path E:\wamp\www\my_website/modules/help/controllers/default/ on my pc I get shown the IndexAction.php Can someone help me?

The stand alone action is in a subdirectory of controllers. So the namespace schould be

namespace app\modules\help\controllers\default;

But that causes this error:

 PHP Parse Error – yii\base\ErrorException
 syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)

EDIT

If I use this namespace app\modules\help\controllers\IndexAction in the IndexAction.php I get the following Error. Even if I change the route in the controller I get the unknownClassException:

Unknown Class – yii\base\UnknownClassException
Unable to find 'app\modules\help\controllers\default\IndexAction' in file: E:\wamp\www\my_website/modules/help/controllers/default/IndexAction.php. Namespace missing?

And if I use this namespace app\modules\help\controllers\default in the IndexAction.php I get this:

 PHP Parse Error – yii\base\ErrorException
 syntax error, unexpected 'default' (T_DEFAULT), expecting identifier (T_STRING)

Solution

As D.Mill says in his comment. default is a reserved keyword. I had to rename the directory and it now works quite fine.



Answered By - EvilKarter
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 5, 2022

[FIXED] Setup a project with Composer by using custom repositories and packages

 March 05, 2022     composer-php, namespaces, php     No comments   

Issue

I am trying to setup a composer project that will enable me to setup my own framework and pulling out any given dependency stored in github private repos.

First some prerequisites:

  1. I don't want to add code to packagist.
  2. I want to make sure my vendor folder is as clean as possible.

Framework composer.json

{
    "name": "mycompany/myframework",
    "description": "YET another Framework",
    "type": "project",        
    "repositories": [
        {
          "type": "package",
          "package": {
             "name": "mycompany/system",
             "version": "0.0.2",
             "type": "library",
             "source": {
                "url": "https://github.com/mycompany/system.git",
                "type": "git",
                "reference": "master"
             }            
          }
       }
   ],
   "require": {                
       "mycompany/system": "0.0.2",
       "mnsami/composer-custom-directory-installer": "1.1.*"        
   },    
   "license": "proprietary",
   "authors": [...],      
   "extra":{
       "installer-paths":{}
   }
}

mycompany/system composer.json

{
    "name": "mycompany/system",
    "type": "library",
    "description": "utility belt xD"
}

The code for the class in PHP ( from mycompany/sytem ) has the following structure:

namespace MYCOMPANY;
//this file name is called utils.php
//adherence to PSR-4 is assumed
class utils  {

}

My goal is:

I want to tell composer that it should create the following structure :

vendor \ MYCOMPANY \ utils.php ( not vendor \ mycompany \system \utils.php )

Later on, I want to be able to add more repositories like this and store them under MYCOMPANY as well. The framwework will work around this setup.

Custom installation is handled by mnsami/composer-custom-directory-installer

I'm guessing I should keep, by rule of thumb, the different packages in their own directories, but, since there is no risk of overwriting because other files will have a different naming convention.

Edit Can this be done? If so, how?

Thank you in advance


Solution

After some hours of work and following on @NicoHaase's reply in the comments, I gave up on this issue.

I was trying to make a clean folder where I would put all the different classes from different repos, but composer just doesn't work that way.

I hope this will help others that want the same thing.



Answered By - jarodium
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Attempted to load class "ClassName" from namespace (...). Even though namespace is imported

 March 05, 2022     namespaces, php, symfony     No comments   

Issue

I have a Symfony project to which I added some non-symfony php files containing various classes. But for some reason the classes are not loaded when loading the website, even though the IDE sees them properly.

So, I have a class that needs other classes:

namespace rootspace\FrontBundle\Controller;

use rootspace\FrontBundle\Networks\TwitterOAuth;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class TwitterController extends Controller
{
    public function connectAction(){
        // The TwitterOAuth instance
        $connection = new TwitterOAuth('abc', '123');
    }
}

And then the class which fails to load (that needs yet another file)

namespace rootspace\FrontBundle\Networks;

/* Load OAuth lib. You can find it at http://oauth.net */
//require_once('OAuth.php'); -- should this be commented out?

/**
 * Twitter OAuth class
 */
class TwitterOAuth {
  /* Contains the last HTTP status code returned. */
}

Lastly, the third file

namespace rootspace\FrontBundle\Networks;
use Symfony\Component\Config\Definition\Exception\Exception;

class OAuthConsumer
{
    public $key;
    public $secret;
}
(...)

I assume the actual filenames don't matter, right? Nor their structure? PhpStorm sees all the classes properly, I can right-click through them, but it fails when deployed.

Thanks for help

Edit - the whole error message says

Attempted to load class "TwitterOAuth" from namespace "rootspace\FrontBundle\Networks" in D:\Dropbox\project\src\rootspace\FrontBundle\Controller\TwitterController.php line 15. Do you need to "use" it from another namespace?

Solution

This is because Symfony's autoloader follows PSR standards (PSR-0, PSR-4) which says that fully qualified (with namespace) class name translates to file location and name. So in fact file names does matter. So in your case rootspace\FrontBundle\Networks\TwitterOAuth class should be located in rootspace/FrontBundle/Networks directory in file called TwitterOAuth.php

If classes you are using does not follow PSR standards you can also register them manually in app/autoloader.php file

Check these for more info:

How can I add a namespace to Symfony 2.1?:

How to autoload class

And check this answer



Answered By - Tomasz Madeyski
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, March 3, 2022

[FIXED] PHP adding custom namespace using autoloader from composer

 March 03, 2022     autoload, composer-php, namespaces, php     No comments   

Issue

Here is my folder structure:

Classes
  - CronJobs
    - Weather
      - WeatherSite.php

I want to load WeatherSite class from my script. Im using composer with autoload:

$loader = include(LIBRARY .'autoload.php');
$loader->add('Classes\Weather',CLASSES .'cronjobs/weather');
$weather = new Classes\Weather\WeatherSite();

Im assuming the above code is adding the namespace and the path that namespace resolves to. But when the page loads I always get this error:

 Fatal error: Class 'Classes\Weather\WeatherSite' not found

Here is my WeatherSite.php file:

namespace Classes\Weather;

class WeatherSite {

    public function __construct()
    {

    }

    public function findWeatherSites()
    {

    }

}

What am I doing wrong?


Solution

You actually don't need custom autoloader, you can use PSR-4.

Update your autoload section in composer.json:

"autoload": {
    "psr-4": {
        "Classes\\Weather\\": "Classes/CronJobs/Weather"
    }
}

To explain: it's {"Namespace\\\": "directory to be found in"}

Don't forget to run composer dump-autoload to update Composer cache.

Then you can use it like this:

include(LIBRARY .'autoload.php');

$weather = new Classes\Weather\WeatherSite();


Answered By - Tomas Votruba
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 9, 2022

[FIXED] Unable to load class php-ds classes in PHP 7 as I get fatal error:class not found

 February 09, 2022     composer-php, data-structures, namespaces, php     No comments   

Issue

I am new to PHP 7 development and I have started working with Composer and PHP. I need to use PHP 7 Data structure like Vector and Stack etc. For this I have created a composer.json in my root directory to require php DS. After composer install, it has created a folder called Vendor and the PHP ds folder is inside it.

I am using the below code in a robots.php file inside the root directory.

<?php
use Ds\Stack;
use Ds\Vector;

$Vector = new Vector();

$stack = new  Stack(); 

I get fatal error saying class not found. I am not aware of how the autoloading works completely. Will I be able to call these class from my php file in the root folder?


Solution

Autoloading

For libraries that specify autoload information, Composer generates a vendor/autoload.php file. You can simply include this file and start using the classes that those libraries provide without any extra work:

require __DIR__ . '/vendor/autoload.php';

use Ds\Stack;
use Ds\Vector;

$Vector = new Vector();

$stack = new  Stack(); 

I suggest you take a look at https://getcomposer.org/doc/01-basic-usage.md



Answered By - Azael
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Autoloading of classes through composer does not work

 February 09, 2022     composer-php, namespaces, php, psr-4     No comments   

Issue

I have a project structure:

enter image description here

In the index.php I create 2 new objects:

use App\Controllers\Test;
use Xuborx\Cms\App;

new Test();
new App();

My Test.php

<?php

namespace App\Controllers;

class Test
{

}

My App.php

<?php

namespace Xuborx\Cms;

class App {

}

My autoload object in composer.json:

"autoload": {
        "psr-4": {
            "App\\Controllers\\": "app/controllers",
            "Xuborx\\Cms\\": "vendor/xuborx/cms"

        }
    }

Object Test created successfully in the index.php, but when I am creating new App, I have an error:

Fatal error: Uncaught Error: Class 'Xuborx\Cms\App' not found in /home/denis/Coding/xuborx-cms/public/index.php:8 Stack trace: #0 {main} thrown in /home/denis/Coding/xuborx-cms/public/index.php on line 8

Also, when I run composer dump-autoload -o, I get error:

Class Xuborx\Cms\App located in ./vendor/xuborx/cms/core/App.php does not comply with psr-4 autoloading standard. Skipping.

I think, I not correct use autoload in composer.json, but I don't understand my error. Please< talk me about it.


Solution

App.php are inside /core directory :

autoload": {
        "psr-4": {
            "App\\Controllers\\": "app/controllers",
            "Xuborx\\Cms\\": "vendor/xuborx/cms/core"

        }
    }


Answered By - Lasouze
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, February 8, 2022

[FIXED] composer dump-autoload -o skips all my classes

 February 08, 2022     composer-php, namespaces, php     No comments   

Issue

I just upgraded to Composer 2.0 which has apparently made some modifications to how it parses classes...

composer dump-autoload -o or the alias composer du -o basically dumps a lot of lines in my console with text like:

Class MyProject\SubCategory\CoolClass located in C:/udvikling/MyProjectRoot/src/MyProjectClasses\MyProject\SubCategory\CoolClass.php does not comply with psr-4 autoloading standard. Skipping

After reading Composer psr-4 autoload issue i ensured that all names that contribute to my namespaces and classpaths are capitalized. i.e. use myproject/helperclass is now use MyProject/HelperClass

My C:/udvikling/MyProjectRoot/src/composer.json includes the following

    "autoload": {
        "psr-4": {
            "MyProject\\": "MyProjectClasses/"
        }
    }

I made one go away by adding a leading backslash to the classname:

<?php

namespace \MyProject\Core;

class Timer {
    //...

but... according to php.net

Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions.

So this seems to not be the right choice... (my IDE also gave me an angry squiggly line under it...)

Besides going back to another version of composer, how do I fix this?

File structure:

C:\udvikling\MyProjectRoot -- the root of the project
C:\udvikling\MyProjectRoot\src --the php sources
C:\udvikling\MyProjectRoot\src\MyProjectClasses -- my PHP classes
C:\udvikling\MyProjectRoot\src\vendor -- my vendor stuff for composer
C:\udvikling\MyProjectRoot\src\composer.json - my composer config


Solution

I went and did some extra reading.

Apparently one of the goals of psr-4 is to reduce the folder depth.

The “src” and “tests” directories have to include vendor and package directory names. >This is an artifact of PSR-0 compliance.

Many find this structure to be deeper and more repetitive than necessary. This proposal suggests that an additional or superseding PSR would be useful [...]

It’s difficult to implement package-oriented autoloading via an extension or amendment to PSR-0, because PSR-0 does not allow for an intercessory path between any portions of the class name.

So basically, the issue was that inside my MyProjectClasses directory, for the class MyProject\Core\Timer I had it in a similar directory structure: C:\udvikling\MyProjectRoot\src\MyProjectClasses\MyProject\Core\Timer.php.
This had to be altered to that the base package was not included: C:\udvikling\MyProjectRoot\src\MyProjectClasses\Core\Timer.php



Answered By - JoSSte
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make propel build models with namespaces in the right directory?

 February 08, 2022     autoload, composer-php, namespaces, php, propel     No comments   

Issue

Default directory for my classes is: app/

Composer autoload config is:

{
    "autoload": {
        "psr-4": { "App\\": "app/" }
    }
}

On propel's schema.xml my namespace is "App\Models"

<database name="default" defaultIdMethod="native"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="http://xsd.propelorm.org/1.6/database.xsd"
          namespace="App\Models"
        >
    <table name="user">
        <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
        <column name="email" type="varchar" size="255" required="true"/>
        <column name="password" type="varchar" size="60" required="true"/>
        <column name="country_id" type="integer" required="true"/>
        <column name="timezone" type="varchar" size="50" required="true"/>
        <foreign-key foreignTable="country">
            <reference local="country_id" foreign="id"/>
        </foreign-key>
    </table>

    <table name="country">
        <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
        <column name="name" type="varchar" size="128" required="true"/>
    </table>
</database>

My propel.php.dist is:

<?php
return [
    'propel' => [
        'paths' => [
            // The directory where Propel expects to find your `schema.xml` file.
            'schemaDir' => 'database/schemas',

            // The directory where Propel should output generated object model classes.
            'phpDir' => 'app/Models'
        ]
    ]
];

When I execute vendor/bin/propel model:build the resulting structure is like this:

/app/
|___Models/
    |___App/
        |___Models/
            |___Base/
            |___Map/
            |___Country.php
            |___CountryQuery.php
            |___User.php
            |___UserQuery.php

I need the structure to be like this:

/app/
|___Models/
    |___Base/
    |___Map/
    |___Country.php
    |___CountryQuery.php
    |___User.php
    |___UserQuery.php

I tried every combination in this manual: Database Attributes

Is there a different way to approach this?

Thanks in advance.


Solution

The configuration specified in the question looks correct, except for one thing that is missing, which made it work in my case: set namespaceAutoPackage to false. In the case of the question's php configuration file, that looks like this:

<?php
return [
    'propel' => [
        'paths' => [
            // The directory where Propel expects to find your `schema.xml` file.
            'schemaDir' => 'database/schemas',

            // The directory where Propel should output generated object model classes.
            'phpDir' => 'app/Models'
        ],
        'generator' => [
            'namespaceAutoPackage' => 'false'
        ]
    ]
];


Answered By - RayOnAir
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 6, 2022

[FIXED] Symfony " 'use' statement for another namespace?" issue

 February 06, 2022     namespaces, symfony     No comments   

Issue

I have a problem with namespaces in connecting my entity class to an abstract-type class.

I needed to create an AbstractType Class I called BlogFactory. I intent to use it in my the createAction function of my BlogController.php Entity class for creating blog entries.

My BlogFactory class is created in the Form/Blog directory of my bundle, as the tree structure shows.

.
.
.
src/Blogger/BlogBundle/
├── Controller
│   ├── BlogController.php
│   └── PageController.php
├── DataFixtures
│   └── ORM
│       └── BlogFixtures.php
├── Entity
│   ├── Blog.php
│   ├── Blog.php~
│   └── Enquiry.php
├── Form
│   ├── Blog
│   │   ├── BlogFactory.php
│   │   └── Factory.php
│   └── EnquiryType.php
├── Resources
│   ├── config
│   │   ├── config.yml
│   │   ├── routing.yml
│   │   └── services.yml
.
.
.

In the BlogController.php entity class, I include the following use instruction:

namespace Blogger\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Blogger\BlogBundle\Form\Blog\BlogFactory;

class BlogController extends Controller{
.
.
.

with the following createAction function:

public function createAction(){   
        $form = $this->createForm(new BlogFactory(), new Blog(), 
            array(
                'action' => $this->generateUrl('blog_create'),
                'method' => 'POST',
            )
        );

        $form->add('submit', 'submit', array('label'=>'Create'));
        return $form;
    }

Here is the code in my BlogFactory class:

namespace Blogger\BlogBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class BlogFactory extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title');
        $builder->add('author');
        $builder->add('blog');
        $builder->add('image');
    }

    public function getName()
    {
        return 'newblog';
    }
}

However, my problem is I get the following error:

The autoloader expected class "Blogger\BlogBundle\Form\Blog\BlogFactory" to be defined in file "/var/www/Symfony-Blog/src/Blogger/BlogBundle/Form/Blog/BlogFactory.php". The file was found but the class was not in it, the class name or namespace probably has a typo

I'm quite stuck and not sure how to resolve this.

UPDATE:

As suggested by Gnucki, I added namespace Blogger\BlogBundle\Form\Blog; to my BlogFactory.php and use Blogger\BlogBundle\Form\Blog\BlogFactory; to BlogController.php, and got the slightly different error below:

Attempted to load class "Blog" from namespace "Blogger\BlogBundle\Controller".
Did you forget a "use" statement for another namespace?

Solution

There is a problem of mapping between your directories and namespaces:

You say that the class BlogFactory is in Form/Blog/BlogFactory.php and you define the class in the namespace Blogger\BlogBundle\Form.

You should use this namespace for your class BlogFactory:

namespace Blogger\BlogBundle\Form\Blog;

Then specify these use statements in your controller:

use Blogger\BlogBundle\Form\Blog\BlogFactory;
use Blogger\BlogBundle\Entity\Blog;

Explanation:

In a simple PHP application, you use some require or include to include files into each other. But it is really boring. Instead, you can use an autoload function to handle that. Symfony2 implements it in a manner that a namespace is mapped on a directory in a logical way. For instance, class Blogger\BlogBundle\Entity\Blog can be found in /Blogger/BlogBundle/Entity/Blog.php.

If you want to use the class in another one (with another namespace (so another directory)), you can use for example:

new \Blogger\BlogBundle\Entity\Blog();

or:

use Blogger\BlogBundle\Entity\Blog;

new Blog();

Imagine, you are in another namespace whitout that use:

namespace Blogger\BlogBundle\Controller;

new Blog();

The class Blog will be interpreted as class Blogger\BlogBundle\Controller\Blog.

namespace Blogger\BlogBundle\Controller;

use Blogger\BlogBundle\Entity\Blog;

new Blog();

Now, with the use, Blog will be interpreted as Blogger\BlogBundle\Entity\Blog.

See namespaces in PHP for more informations.



Answered By - Gnucki
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 5, 2022

[FIXED] Can we add subdirectory manually after the psr-4 composer namespace path?

 February 05, 2022     autoload, composer-php, namespaces, php, psr-4     No comments   

Issue

I have different versions of files which are stored in separate subfolders inside a main folder. I intend to use subfolder based on a dynamically determined value of $ver.
Can I create a psr-4 composer namespace for the main folder and then add to it the $ver for subfolders as needed.
I tried following but its showing errors.

File Structure:

web\  
  public\index.php 
  main\
        V1\app.php
        V2\app.php
        V3\app.php

Composer:

    "autoload": {
        "psr-4": {
            "Application\\": "main"
        }
    }

index.php:

use Application;

$ver = "V2"; // suppose its V2 for now

$app = new "\Application\" . $ver . "\App()";

app.php:

namespace Application;  
class App {

}


Solution

You must follow PSR-4 for class naming and app structure:

composer.json
    "autoload": {
        "psr-4": {
            "Application\\": "main"
        }
    }
main/V1/App.php
    namespace Application\V1;
    class App {}

For instance class with dynamic name use next construction:

$ver = "V2"; // suppose its V2 for now
$appClass = "\Application\$ver\App";
$app = new $appClass;

Read more about this here

And i recommend to use factory pattern for this case:

class App implements AppInterface {}
class AppFactory
{
    public static function makeApp(string $version): AppInterface
    {
         $appClass = "\Application\$version\App";
         if(! class_exists($appClass){
             throw new Exception("App version $version not exists");
         }
         return new $appClass;
    }
}


Answered By - Maksim
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing