Содержание
- [BUG] [Symfony 3.0] [PHP 7] Cannot declare class Locale, because the name is already in use #20532
- Comments
- Cannot declare class because the name is already in use #374
- Comments
- Ошибка Cannot declare class
- Cannot declare class m140209_132017_init, because the name is already in use #13989
- Comments
- What steps will reproduce the problem?
- What is the expected result?
- What do you get instead?
- Additional info
- Footer
[BUG] [Symfony 3.0] [PHP 7] Cannot declare class Locale, because the name is already in use #20532
I got the following error in the console, when using a translation within a twig file (not sure if it’s only in twig):
Info about environment:
xenial+1 (cli) ( NTS )
Symfony 3.0.1
The text was updated successfully, but these errors were encountered:
This looks weird. Can you explain which step you performed that ended up here? Did you switch PHP versions, but did not clear the cache?
First I upgraded to 3.0.1, after a succesful upgrade, i switched to PHP 7.0. I can confirm this issue is not a cache issue. I forced cleared the cache by removing the folder cache content (rm ./var/cache/prod/; rm ./var/cache/dev/), but that does not solve anything.
I got the issue!
The following rule causes the error:
$c = SymfonyComponentLocaleLocale::getDisplayCountries(‘nl’);
I replaced the code with the following code:
$c = Intl::getRegionBundle()->getCountryNames(‘nl’);
But this strange (Declare) error should not may appear!
Same here with Symfony 3.2, PHP 7.0.14-2+deb.sury.org
xenial+1
but with Response class
Cannot declare class SymfonyComponentHttpFoundationResponse, because the name is already in use in /var/www/var/cache/prod/classes.php on line 4479
In prod environment it seems to appear when using the HttpCache with AppCache().
Well, I found this issue with the use of FOSHttpCacheBundle FriendsOfSymfony/FOSHttpCacheBundle#276
afair this is because of a hard to reproduce bug in opcache try completely disabling it.
@thi3rry your issue is different and should be solved by #21184
@RubenHarms can we close this issue then?
Closing due to no response.
@RubenHarms feel free to come back with more details and we’ll re-open.
I got the same issue with SymfonyComponentConfigConfigCacheInterface
Источник
Cannot declare class because the name is already in use #374
Following the tutorial, as it is, for a project I am working on gave ‘class not found exception’ in:
- configuring the ApplicationAspectKernel in the front controller,
- registering aspect in aspect kernel, and
- declaring pointcut in an aspect for the methods of some class
To solve this, I added include statements:
- include ‘../application/ApplicationAspectKernel.php’; for my project’s front controller
- include ‘aspect/MonitorAspect.php’; in ApplicationAspectController.php
- include ‘../application/controller/CallbackController.php’; in MonitorAspect.php (CallbackController is the class whose methods I want to intercept).
On doing this I get the error PHP Fatal error: Cannot declare class CallbackController, because the name is already in use in /var/www/html/vyom-crm-frontend/application/controller/CallbackController.php on line 0
[Edit]: I removed the third include above. This resolved the above error. Now, the interceptor didn’t work with the following pointcut
This pointcut works — @Before(«execution(public **->*(*))»)
But I don’t want to intercept all methods of all classes. There is a specific method in CallbackController that I want to intercept.
Please help me solve this. Thanks!
The text was updated successfully, but these errors were encountered:
It seams that you are not using Composer (https://getcomposer.org) for auto loading classes?
In order for Go! AOP to work properly, usage of Composer as class autoloader is u must.
@TheCelavi I am using Composer. Code in my index.php —
Hi, your init section looks invalid. Where is your appDir setting? And you should always configure the cacheDir option in order to have good performance.
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence.
Could you also show the namespace of your CallbackController ? And please, report your version of framework too.
@lisachenko
your init section looks invalid. Where is your appDir setting — Couldn’t follow what you mean. Which part are you calling the ‘init section’ and which settings are appDir settings?
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.
Could you also show the namespace of your CallbackController — It has no declared namespace.
report your version of framework — ^2.1
appDir — (sorry, not documented setting, will be fixed with new documentation) a path which points to a rood folder of your project/application source. includePaths is optional and should point to additional directories where your source code residue (or at least, code which should be weaved.). If you are familiar with Symfony — you may see Go! AOP Symfony bundle for reference.
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.
If you are getting «class not found» exception when loading your class — that means that Composer is not all setup properly to load your classes.
In general, if Composer is setup properly (and you are using Composer for class autoloading) — beside «require ‘../vendor/autoload.php’;» you should not have any need to use require , include and so on. for class loading in your project, except, of course, in your app entry script (e.g. index.php)
If you are getting «Cannot declare class CallbackController, because the name is already in use» that simply means what it said — CallbackController is being loaded twice. It is going to be hard to give you any more info if there is no full insight in application code (at least for me, maybe Alexandar would have more luck).
Источник
Ошибка Cannot declare class
| Цитата |
|---|
| Федор Михайлов написал: Может быть есть другие советы |
| Цитата |
|---|
| Павел Петриенко написал: если судить по аналогии с файлами element.php & elementtable.php |
| Цитата |
|---|
| Антон Егоров написал: Если это особенность обновления, то может быть это нужно задокументировать, с пометкой «после обновления удалите вручную такой-то файл». |
Здравствуйте. У меня возникла похожая проблема но с компонентом меню.
Несколько лет назад была сделана копия этого компонента для кастомизации в папку «/bitrix/components/user/menu/», которая и использовалась. При этом платформа периодически обновлялась. Однако несколько месяцев назад было решено подключить меню из папки «/bitrix/components/bitrix/menu/», что вызвало следующую ошибку:
| Цитата |
|---|
| Olgert написал: Подскажите пожалуйста как исправить эту проблемму? |
| Цитата |
|---|
| Olgert написал: Подскажите пожалуйста как исправить эту проблемму? |
Либо не использовать оба компонента одновременно, либо (что самое правильное и так нужно было сделать изначально) переименовать класс в кастомизированном компоненте.
Спасибо!
Действительно оказалось что на странице использовалось еще одно меню из папки «/bitrix/components/user/menu/». И когда я переподключил нужное меню из папки «bitrix» второе осталось подключенным из папки «user» и это вызвало ошибку. Спасибо буду знать.
З.Ы. Если что наш сайт не коммерческий и поддерживается полупрофессионалом.
В моем случае были ошибка «Cannot declare class BitrixIblockElementTable, because the name is already in use», при этом страница открывалась в браузере, но выдавала ошибку 500. Данную ошибку вызывал типовой компонент «Просмотренные товары».
Источник
Cannot declare class m140209_132017_init, because the name is already in use #13989
What steps will reproduce the problem?
What is the expected result?
What do you get instead?
Additional info
| Q | A |
|---|---|
| Yii version | yiisoft/yii2 dev-master 03e0607 Yii PHP Framework Version 2 |
| PHP version | PHP 7.1.3 (cli) (built: Mar 17 2017 22:24:22) ( NTS ) |
| Operating system | Debian |
The text was updated successfully, but these errors were encountered:
do you have an other migration with that name?
I find problem
no set namespace in the migration file
new feature so new
After I put namespace into a migration class file
I still can do apply the migration without config
Note: migrations specified via [[yiiconsolecontrollersMigrateController::migrationPath|migrationPath]] can not contain a namespace, namespaced migration can be applied only via [[yiiconsolecontrollersMigrateController::migrationNamespaces]] property.
We will add namespaces to migrations
#13918
The migration with namespace still work in the old project (i.e. module migration)?
I’m not sure that I’ve got your question.
Current schema (not ideal):
Apply migration in project without namespace ./yii migrate/up
Apply migration from vendor module without namespace ./yii migrate/up —migrationPath=@yii/rbac/migrations/
Module have update, migration have namespace now. Project not modified.
BC: Migration in module must still work with old syntax. (Autoload must use any of both method)
Could you re-post this message to #13918 and we will continue discussion there?
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
samyak45 opened this issue
Dec 8, 2017
· 24 comments
Comments
Following the tutorial, as it is, for a project I am working on gave ‘class not found exception’ in:
- configuring the ApplicationAspectKernel in the front controller,
- registering aspect in aspect kernel, and
- declaring pointcut in an aspect for the methods of some class
To solve this, I added include statements:
- include ‘../application/ApplicationAspectKernel.php’; for my project’s front controller
- include ‘aspect/MonitorAspect.php’; in ApplicationAspectController.php
- include ‘../application/controller/CallbackController.php’; in MonitorAspect.php (CallbackController is the class whose methods I want to intercept).
On doing this I get the error PHP Fatal error: Cannot declare class CallbackController, because the name is already in use in /var/www/html/vyom-crm-frontend/application/controller/CallbackController.php on line 0
[Edit]: I removed the third include above. This resolved the above error. Now, the interceptor didn’t work with the following pointcut
@Before("execution(public CallbackController->*(*))")
This pointcut works — @Before("execution(public **->*(*))")
But I don’t want to intercept all methods of all classes. There is a specific method in CallbackController that I want to intercept.
Please help me solve this. Thanks!
It seams that you are not using Composer (https://getcomposer.org) for auto loading classes?
In order for Go! AOP to work properly, usage of Composer as class autoloader is u must.
@TheCelavi I am using Composer. Code in my index.php —
<?php
// Auto-loading the classes (currently only from application/libs) via Composer's PSR-4 autoloader
// Later it might be useful to use a namespace here, but for now let's keep it as simple as possible
require '../vendor/autoload.php';
include_once '../application/ApplicationAspectKernel.php';
if(class_exists('ApplicationAspectKernel')) {
// Initialize an application aspect container
$applicationAspectKernel = ApplicationAspectKernel::getInstance();
$applicationAspectKernel->init(array(
'debug' => true, // use 'false' for production mode
// Cache directory
'cacheDir' => null,
// Include paths restricts the directories where aspects should be applied, or empty for all source files
'includePaths' => array(
__DIR__.'/../application/'
)
));
}
else {
error_log("class ApplicationAspectKernel not found");
}
// Start our application
new Application();
?>
Hi, your init section looks invalid. Where is your appDir setting? And you should always configure the cacheDir option in order to have good performance.
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence.
Could you also show the namespace of your CallbackController? And please, report your version of framework too.
@lisachenko
your init section looks invalid. Where is your appDir setting — Couldn’t follow what you mean. Which part are you calling the ‘init section’ and which settings are appDir settings?
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.
Could you also show the namespace of your CallbackController — It has no declared namespace.
report your version of framework — ^2.1
appDir — (sorry, not documented setting, will be fixed with new documentation) a path which points to a rood folder of your project/application source. includePaths is optional and should point to additional directories where your source code residue (or at least, code which should be weaved.). If you are familiar with Symfony — you may see Go! AOP Symfony bundle for reference.
You should also remove first include for ApplicationAspectKernel.php and additional check for class existence. — that gives class not found exceptions.
If you are getting «class not found» exception when loading your class — that means that Composer is not all setup properly to load your classes.
In general, if Composer is setup properly (and you are using Composer for class autoloading) — beside «require ‘../vendor/autoload.php’;» you should not have any need to use require, include and so on… for class loading in your project, except, of course, in your app entry script (e.g. index.php)
If you are getting «Cannot declare class CallbackController, because the name is already in use» that simply means what it said — CallbackController is being loaded twice. It is going to be hard to give you any more info if there is no full insight in application code (at least for me, maybe Alexandar would have more luck).
@TheCelavi parts of the application code that might be helpful —
index.php
<?php
require '../vendor/autoload.php';
$applicationAspectKernel = ApplicationAspectKernel::getInstance();
$applicationAspectKernel->init(array(
'debug' => true, // use 'false' for production mode
// Cache directory
'appDir' => '../application/',
'cacheDir' => null,
// Include paths restricts the directories where aspects should be applied, or empty for all source files
'includePaths' => array(
'../application/'
)
));
// Start our application
new Application();
composer.json
{
"name": "Inventory",
"type": "project",
"description": "Inventory",
"keywords": ["mvc"],
"homepage": "https://rightklick.in/",
"license": "MIT",
"require-dev": {
"php": ">=5.5.0"
},
"autoload": {
"psr-4": { "": ["application/core/", "application/model/"] }
},
"require": {
"goaop/framework": "^2.1"
}
}
autoload.php
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c::getLoader();
autoload_real.php
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c
{
private static $loader;
public static function loadClassLoader($class)
{
if ('ComposerAutoloadClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c', 'loadClassLoader'), true, true);
self::$loader = $loader = new ComposerAutoloadClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit4dad9c0cc8cbc9a8baecb2ef83f1193c', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(ComposerAutoloadComposerStaticInit4dad9c0cc8cbc9a8baecb2ef83f1193c::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = ComposerAutoloadComposerStaticInit4dad9c0cc8cbc9a8baecb2ef83f1193c::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire4dad9c0cc8cbc9a8baecb2ef83f1193c($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire4dad9c0cc8cbc9a8baecb2ef83f1193c($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}
@TheCelavi @lisachenko does the above part of the application code help understanding what am I doing wrong?
Hi, only missing option is cacheDir right now, strange that it still works for you, because there should be an exception. All other settings look ok…
@lisachenko but I am still not being able to define pointCut specific for the class/method I want to intercept.
This works — @Before("execution(public **->*(*))")
This doesn’t — @Before("execution(public CallbackController->*(*))")
@lisachenko I am still having to use include_once '../application/ApplicationAspectKernel.php'; without it the error PHP Fatal error: Uncaught Error: Class 'ApplicationAspectKernel' not found still comes.
I am still having to use include_once ‘../application/ApplicationAspectKernel.php’;
This is because your configuration for PSR-4 is incorrect:
"autoload": {
"psr-4": { "": ["application/core/", "application/model/"] }
},
Please, add "application/" directory to this list or move this ApplicationAspectKernel.php file into your core directory, so composer will be able to find it.
This doesn’t — @before(«execution(public CallbackController->())»)
Please, give me full path and content of this CallbackController file (without method bodies), including the namespaces, uses, includes, etc. And several methods (only names, without bodies).
class not found errors resolved. For the pointcut part:
give me full path and content of this CallbackController file (without method bodies), including the namespaces, uses, includes, etc. And several methods (only names, without bodies).
full path — <project_folder>/application/controller/CallbackController.php
namespace — none (no namespaces have been used in the controllers and models of this project)
includes — none
extends — Controller
methods — foo() (there is only one method apart from the constructor.)
PHP Fatal error: Uncaught Error: Class ‘aspectMonitorAspect’ not found
It’s the same, you have not configured autoload section in your composer.json file. Just move to application/core directory or adjust your composer.json file. Also, remove aspect namespace in this file — you should either configure autoloader or clean it if you move it into the application/core directory. After that aspect will be registered and AOP should apply to your files.
From what I can see, all troubles in this issue are because of wrong composer configuration/autoloading initialization.
@lisachenko the class not found errors were resolved. (As I said in my previous comment). The pointcut issue remains.
To attempt to solve the pointcut issue I, —
- Added namespace
controllercallbackto CallbackController.php. - Since CallbackController extends Controller, added namespace corecontroller to Controller.php containing the parent class Controller, and added
use corecontrollerController;to CallbackController.php - Added a
use controllercallback;statement to MonitorAspect.php
This gave new errors: PHP Fatal error: Class ‘Controller’ not found. (Class Controller is in application/core should be auto included.
@lisachenko my composer autoload settings now are —
"autoload": {
"psr-4": { "": ["application/core/", "application/model/", "application/controller/", "application/aspect/"] }
},
Also I have successfully run composer update after changing conposer.json (this is what resolved class not found on MonitorAspect).
@samyak45 Please, resolve all class «xxx» not found errors before asking about help, as I’m sure that it’s simple incorrect configuration of composer. If you have troubles in configuring composer loader, then I would recommend you not to use AOP for a while, because knowing PSR-0,4 standards is must have.
To debug all class XXX not found, just create new instances of them right after include of autoload file.
require '../vendor/autoload.php';
You should be able to create instance of aspect kernel, aspect instance, your controller instance.
After that we can check why it’s not working for you.
@lisachenko is using namespaces necessary to use goaop?
This works without having to use namespaces in my project @Before("execution(public **->*(*))")
But @Before("execution(public CallbackController->*(*))") doesn’t work for functions inside controller. (Though it does work for the constructors of controller classes.)
Also, I am being able to intercept methods of CallbackModel used by CallbackController using @Before("execution(public CallbackModel::*(*))"). However, I want to intercept at controller level.
@lisachenko is using namespaces necessary to use goaop?
No it isn’t necessary, engine can work with global namespace too.
Just for fun, try to use @Before("execution(public ***Contr*->*(*))") Who knows…
In order to find out what is the root cause you should debug why pointcut isn’t matched for your class.
You have definitely some typo somewhere: in classname or in the pointcut…
PS: I’m right that methods in your controller are not final?
Just for fun, try to use @before(«execution(public **Contr->())») Who knows.
Doesn’t work.
You have definitely some typo somewhere: in classname or in the pointcut…
No. I have rechecked. Have also got other members of my team to review but no luck.
I’m right that methods in your controller are not final
No. They are not.
One thing though — the controllers in my project convert to url by the logic — all controller classes must end with the string ‘Controller’. When hitting any controller named Controller, you don’t need to put ‘Controller’ in the url, just ‘<base_url>/x/<controller_method> works.
Does above information help?
PS: Using @Before("execution(public **->*(*))") intercepts the controller constructor but no other methods.
@samyak45 have no idea what is wrong 
I have tried to reproduce you case:
composer create-project goaop/framework- Created
demos/controllerdirectory and putCallbackController.phpfile with following content:
<?php class CallbackController { public function testHello() { echo "yay!"; } }
- In the
autoload_aspect.phpfile I’ve added
$controller = new CallbackController(); $controller->testHello();
- Changed
LoggingAspectpointcut to the@Before("execution(public CallbackController->*(*))")(I’m using Go! AOP Framework plugin with PhpStorm, so I can see A⬇️ icon in the gutter) - Added into
composer.jsonsection for loading my controller fromdemos/controllerdirectory:
"psr-4": {
"": "demos/controller/"
}
- Warmed composer (in order to generate autoload files)
- Refreshed my page — and everything works:
Calling Before Interceptor for execution(CallbackController->testHello()) with arguments: []
yay!
@lisachenko no I couldn’t solve it so to get my work done for now I added a new function to my CallbackModel, that now does all that happened in CallbackController function I wanted to intercept. And I added interceptor for this function in the model. Architecturally this isn’t right but was compelled to use this hack to get work done.
Thanks. You can now close this issue.
Ok, wish you good luck.
Ping me if some help will be required.
|
Пользователь 1214851 Заглянувший Сообщений: 44 |
При открытии существующей задачи, появляется ошибка |
|
Александр Новокшанов, а можете полный текст ошибки со стек-трейсом? |
|
|
Пользователь 1214851 Заглянувший Сообщений: 44 |
Обновлял битрикс 19-го числа. Это все, что выводится на экран. |
|
Пользователь 1890127 Эксперт Сообщений: 400 |
#4 0 08.02.2019 06:15:04
Не решили проблему? У нас то же самое сообщение стало появляться |
||
|
Пользователь 136059 Гуру Сообщений: 5418 |
#5 0 08.02.2019 10:06:10
Обратитесь с тех.поддержку, видимо при обновлении битрикс некорректно обновил технические файлы Голосуй за идеи по развитию API Bitrix: |
||
|
Пользователь 291336 Эксперт Сообщений: 1497 |
#6 0 01.10.2019 11:29:08
такая же проблема — 1С-Битрикс: Управление сайтом 19.0.293 обновление bitrix поможет? Как создать лендинг из любого готового решения Bitrix |
||
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#7 2 01.10.2019 12:17:41
Не такая же — у топик-стартера модуль задач, у вас — инфоблоки. Вариантов два — либо некорректно встало обновление iblock 18.6.700 (апдейтер не смог удалить файл iblock/lib/property.php, например, из-за прав), либо после установки перезаливались файлы модуля.
Нет. Вручную удалите файл iblock/lib/property.php, предварительно проверив, что существует iblock/lib/propertytable.php. А лучше обратитесь в ТП, дав административный доступ. Не надо сверлить зубы через задний проход дрелью от Сваровски |
||||
|
Пользователь 1242451 Заглянувший Сообщений: 13 |
#8 0 12.10.2019 22:36:41
Спасибо, добрый человек) |
||
|
Пользователь 620445 Заглянувший Сообщений: 9 |
Такая ошибка возникает при попытке установить два одинаковых модуля. Можно проверить разместив модуль в директории /loca/modules/ два раза. Даже без установки будет ошибка. |
|
Пользователь 113306 Заглянувший Сообщений: 7 |
#10 2 25.10.2019 19:29:12 Добрый вечер, та же проблема с bitrix/modules/iblock/lib/element.php, bitrix/modules/iblock/lib/elementtable.php
удаление первого помогло и функционал заработал. Но пока только на дев площадке сделал. Вопрос, могу ли быть уверенным, что функционал в других частях сайта не посыпется? |
||||
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#11 0 25.10.2019 19:34:56
Конкретизируйте вопрос.
И по-прежнему ни одного обращения в ТП для попытки выяснения сценария. Не надо сверлить зубы через задний проход дрелью от Сваровски |
||||
|
Пользователь 12233 Заглянувший Сообщений: 23 |
#12 0 06.11.2019 04:50:40 Тикет 2502140 Если с «Cannot declare class BitrixIblockPropertyTable» удалось разобраться , то теперь ещё и «Cannot declare class BitrixIblockIblockTable» вылезло при попытке создания фасетного индекса в админке |
|
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#13 1 06.11.2019 10:49:07 Внимание! Настоятельно рекомендую всем, кто сталкивается с такой проблемой, проверить права доступа на папку /bitrix/modules/. Василий Зайковский, проблема та же самая. Убедитесь, что есть файл /bitrix/modules/iblock/lib/iblocktable.php и удалите /bitrix/modules/iblock/lib/iblock.php. Либо переустановите обновление, убедившись, что с правами доступа все в порядке. Не надо сверлить зубы через задний проход дрелью от Сваровски |
|
Пользователь 12233 Заглянувший Сообщений: 23 |
#14 0 06.11.2019 12:26:27 Да. Всё OK. Помогло! Благодарю! P.S. При полной проверке сообщение «Все проверенные файлы и папки доступны для чтения и записи» |
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#15 0 06.11.2019 12:35:20
Я рад. Не надо сверлить зубы через задний проход дрелью от Сваровски |
||
|
Пользователь 1288159 Заглянувший Сообщений: 32 |
#16 1 23.06.2020 17:19:29
Евгений, а всего навсего нужно выводить ошибку при обнове и отдавать сhangelog администратору что отработало успешно а где затык был. Видимо разработчики битрикса не слышали о таком слове в написание программы как «исключения», не удалось удалить файл, прав не хватило — выведи пользователю сообщение, а не тихо мирно забей. Это признак *** кода.! Научите ваших мастеров писать нормально и пользоваться https://www.php.net/manual/ru/language.exceptions.php У нас таких проблем было несколько практически на свежеустановленом портале ему 2 месяца, права никто не менял и все корректные на всю папку bitrix, но гадость случается и теперь вопрос А КОРРЕКТНО ЛИ ВСЕ ОБНОВЫ ВСТАЛИ? я не могу быть уверенным, а вдруг какой метод не отработал при установке и bitrix умолчал! Ваша поддержка одна из наискорейших, день они могут выяснять стоят ли обновы, второй подключают и передают специалисту, через 2 дня он просит доступ еще через день он начинает в лучшем случае смотреть, и только через неделю от задания вопроса мы получаем ответ. А теперь опять вопрос? как нам неделю работать? На карантин уходить? по причине того что Битрикс24 заболел? Может Битрикс будет оплачивать з/п сотрудникам потому, что у них продукт кривой? |
||
|
Пользователь 4529832 Заглянувший Сообщений: 7 |
#17 0 17.09.2020 14:22:49 Здравствуйте. После обновления Битрикс (до «1С-Битрикс: Управление сайтом 20.0.1700») на все страницах интернет-магазина появилось следующее сообщение: Честно говоря, мне не понятно с чем это связано. Ознакомился с сообщениями в этом разделе форума по теме «Ошибка Cannot declare class». Если я правильно понял, то в папке public_html/bitrix/modules/iblock/lib нужно удалить/переименовать три файла: element.php, iblock.php, property.php. В папке public_html/bitrix/modules/iblock/lib переименовал три файла: element.php, iblock.php, property.php. Помогло! Вышеуказанное сообщение пропало и, по-моему, интернет-магазин работает нормально. ВОПРОС: P.S |
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#18 0 17.09.2020 17:25:59
Эм… А можно поподробней? Есть подозрение, что не совсем правильно. Не надо сверлить зубы через задний проход дрелью от Сваровски |
||
|
Пользователь 247941 Постоянный посетитель Сообщений: 64 |
#19 0 16.10.2020 14:52:48 Евгений, здравствуйте
Не подскажете как можно переустановить обновления? |
||
|
Пользователь 163998 Заглянувший Сообщений: 1 |
#20 0 12.11.2020 09:03:14
Совсем неправильно. Только что потоптался по этим граблям. Два проекта оч давно не обновлялись, пару лет точно. И после обновления в /bitrix/modules/iblock/lib/ обнаружились два файла, объявляющих один и тот же класс. Это были упомянутые выше element.php & elementtable.php, в обоих один и тот же класс
Заглянув в свежеустановленный БУС, увидел, что там нет elementtable.php, а есть только element.php. Поэтому переименовал elementtable.php в elementtable.php.bad Сами файлы практически идентичны:
Что касается вопроса
то однозанчно НЕПРАВИЛЬНО, так как в имеющихся казалось бы тоже дублирующих (если судить по аналогии с файлами element.php & elementtable.php) парах iblock.php/ibloctable.php и property.php/propertytable.php находятся РАЗНЫЕ классы. Впрочем, Вы наверное уже сами убедились, что это непрвильно, пишу для того. чтобы другие нашедшие тему так не поступали. ЗЫ. Евгений Жуков, права однозначно не при чем, на обоих проектах все права были и есть в порядке, проверялись перед обновлением. |
||||||||
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#21 0 12.11.2020 12:51:36
Вы сделали ровно наоборот. Откуда брали дистрибутив и версия iblock в нем? Не надо сверлить зубы через задний проход дрелью от Сваровски |
||
|
Пользователь 247941 Постоянный посетитель Сообщений: 64 |
#22 0 12.11.2020 13:23:40
У меня тоже проблема ушла после устранения этого «наоборот» |
||
|
Пользователь 520591 Посетитель Сообщений: 56 |
#23 0 17.12.2020 00:09:17 При обновлении вылезла вот такая ошибка: Fatal error: Cannot declare class Landing, because the name is already in use in /bitrix/updates/update_mxxxxxxxx/landing/install/index.php on line 727 Подскажите как побороть |
|
Евгений Жуков
Администратор Сообщений: 9035 Epic fail — сказать «это так просто» и не суметь сделать |
#24 1 17.12.2020 11:46:38
Обратиться в ТП с доступом. Не надо сверлить зубы через задний проход дрелью от Сваровски |
||
|
Пользователь 520591 Посетитель Сообщений: 56 |
#25 0 17.12.2020 13:52:58
Спасибо за отклик, но мы не ищем лёгких путей |
||||
Today I received the same-type error:
PHP Fatal error: Cannot declare class ClassNameHere , because the name is already in use in /var/www/m2/magento2/app/code/path/to/the/class.php on line 100
where the line 100 is end of the file.
Approximately after 4 hours of debugging I really find the reason: a misprint in the namespace declaration. Till the final moment I didn’t believe that it is a typographical error in names declaration, but when I have rewritten all names anew — the mistake has disappeared. This article was very helpful:
I’ll scratch my head for a while, wonder what’s going on, and
eventually realize it’s thisPulsetormi.e. I’ve mistyped a namespace name, and when the initial autoloads
loads the class file, it won’t have defined the class it’s looking
for, and then a second autoloader (Composer’s usually) loads it again,
and tries to redefine the same incorrect class.i.e., Magento wanted the class
PulsestormHelloworldObserversBlockbut I defined
PulsetormHelloworldObserversBlockthanks to the wrong namespace.
Thank you, Alan Storm 
UPDATE:
Another type of that error is incorrect Namespace declaration with missing part of the namespace, as in this example:
Error:
Repositories code generation… 1/7 [====>————————]
14% 1 sec 50.0 MiBPHP Fatal error: Cannot declare class
MigrationStepVersion11410to2000Test, because the name is already in
use in
/var/www/vhosts/rwld/vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php
on line 109
where the line 109 is end of the file.
In the file vendor/magento/data-migration-tool/tests/unit/testsuite/Migration/Step/UrlRewrite/Version11410to2000Test.php we found the namespace as MigrationStep when the correct namespace should be MigrationStepUrlRewrite because path to this class is Migration/Step/UrlRewrite. After changing of the namespace to Migration/Step/UrlRewrite the error is gone.
This is an error happened upon executing a command for processing migration script file. The concept itself, the migration script file processing is a concept or not only just a concept but also the implementation offered in Laravel web-based application development to operate with tables represented by each of the migration script file. The file itself is not specified since the process of executing the migration script files are done by executing all of the migration script files located normally in folder ‘/database/migrations’.
All of the migration script files can be executed by typing the following command in the bash prompt :
php artisan migrate:refresh
Below is the output of the above command execution :
user@hostname:/var/www/html/laravel$ php artisan migrate:refresh PHP Fatal error: Cannot declare class CreateCategoriesTable, because the name is already in use in /var/www/html/laravel-support-ticket/database/migrations/2017_11_02_151257_create_categories_table.php on line 31 [SymfonyComponentDebugExceptionFatalErrorException] Cannot declare class CreateCategoriesTable, because the name is already in use user@hostname:/var/www/html/laravel$
In this article context, especially based on the above output generated by executing the commad php artisan migrate:refresh, the process cannot be proceed since it is actually generated an error message as shown in the above output. The error message is actually : “Cannot declare class CreateCategoriesTable, because the name is already in use”.
In the above context, “CreateCategoriesTable” is actually the name of the class specified in the migartion script file. It said that the class name has already exist because in the term of this case, there are three files which has the same name part which in the end there are three migration script files which have the same class name. Although those files are generated in the different time but it actually refers to the same class name. The situation is shown in the following :
user@hostname:/var/www/html/laravel/database/migrations$ ls -al total 16 drwxrwxr-x 2 user user 4096 Nov 5 22:08 . drwxrwxr-x 3 www-data user 4096 Nov 5 22:22 .. ... -rw-rw-r-- 1 www-data user 601 Nov 2 22:06 2017_11_02_150646_create_categories_table.php -rw-rw-r-- 1 www-data user 601 Nov 2 22:12 2017_11_02_151257_create_categories_table.php -rw-rw-r-- 1 www-data user 601 Nov 2 22:19 2017_11_02_151921_create_categories_table.php ... user@hostname:/var/www/html/laravel/database/migrations$
In the context of this article, the solution which I implemented to solve the problem is by moving away the other files unnecessary. Since it can only be one script representing one class, just move the rest of the files into another location. I created one folder in the current path shown above and move the other two older files inside the folder. It is shown as follows :
user@hostname:/var/www/html/laravel/database/migrations$ mkdir temp user@hostname:/var/www/html/laravel/database/migrations$
And move those files unrelated :
user@hostname:/var/www/html/laravel/database/migrations$ mv 2017_11_02_150646_create_categories_table.php 2017_11_02_151257_create_categories_table.php temp/ user@hostname:/var/www/html/laravel/database/migrations$ cd temp user@hostname:/var/www/html/laravel/database/migrations$ ls -al total 16 drwxrwxr-x 2 user user 4096 Nov 5 22:08 . drwxrwxr-x 3 www-data user 4096 Nov 5 22:22 .. -rw-rw-r-- 1 www-data user 601 Nov 2 22:06 2017_11_02_150646_create_categories_table.php -rw-rw-r-- 1 www-data user 601 Nov 2 22:12 2017_11_02_151257_create_categories_table.php user@hostname:/var/www/html/laravel/database/migrations/temp#
Summary: in this tutorial, you’ll learn about PHP namespaces, how to define classes that belong to a namespace, and how to use namespaces.
Why namespaces
When your project grows in complexity, you’ll need to integrate the code from others. Sooner or later, you’ll find that your code has different classes with the same name. This problem is known as name collision.
To resolve it, you can use namespaces. PHP supported namespaces since version 5.3.
What is a namespace
It’s easier to understand namespaces by analogy to the directory structure in a filesystem.
A directory stores related files, which is similar to a namespace that groups related classes.
A directory doesn’t allow you to have two files with the same name. However, you can have files with the same names in different directories. Likewise, namespaces mimic the same principle.
By definition, namespaces provide you with a way to group related classes and help you avoid any potential name collisions.
Namespaces are not limited to group classes. They can group other identifiers, including functions, constants, variables, etc.
Set up a directory structure
First, create a project directory, e.g., store and create a new index.php file in the directory.
Second, create src directory in the project directory and Model directory in the src directory.
Third, create a new file called Customer.php in the Model directory with the following code:
Code language: HTML, XML (xml)
<?php class Customer { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } }
The directory looks like the following:
Code language: plaintext (plaintext)
. ├── index.php └── src └── Model └── Customer.php
Define a namespace
To define a namespace, you place the namespace keyword followed by a name at the very top of the page. The following example gives the Customer class with a namespace StoreModel:
Code language: HTML, XML (xml)
<?php namespace StoreModel; class Customer { private $name; public function __construct($name) { $this->name = $name; } public function getName() { return $this->name; } }
- It’s customary to assign the
srcdirectory theStorenamespace. And you can replaceStorewith your brand name, e.g., Apple. - It’s a good practice to imitate the directory structure with the namespace to find classes more easily. For example, every class within the directory will get the namespace
StoreModel.
Use a class that belongs to a namespace
To use a class that belongs to a namespace in the index.php, you need to include the file and use the class:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; $customer = new Customer('Bob'); echo $customer->getName();
If you open the index.php, you’ll get a fatal error:
Code language: JavaScript (javascript)
Fatal error: Uncaught Error: Class 'Customer' not found in...
Since the Customer class now is namespaced, you need to use the fully qualified name that includes the namespace like this:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; $customer = new StoreModelCustomer('Bob'); echo $customer->getName();
Now, it should work properly.
Import a namespace
To avoid using the fully qualified names from a namespace, you can import the namespace with the use operator like this:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; use StoreModel; $customer = new ModelCustomer('Bob'); echo $customer->getName();
Now, you just need to prefix the class name with Model.
Import a class from a namespace
PHP allows you to import a class from a namespace instead of importing the namespace. For example:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; use StoreModelCustomer; $customer = new Customer('Bob'); echo $customer->getName();
In this example, we use the use operator to import the Customer class from the StoreModel namespace. Therefore, we don’t have to prefix the class name with the namespace.
Import multiple classes from a namespace
First, create a new file called Product.php in the src/Model directory:
Code language: HTML, XML (xml)
<?php namespace StoreModel; class Product { }
For demonstration purposes, the Product class is empty. Now, the directory structure looks like the following:
Code language: plaintext (plaintext)
. ├── index.php └── src └── Model ├── Customer.php └── Product.php
To use both Customer and Product classes from the index.php, you can import them individually like before:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; require 'src/Model/Product.php'; use StoreModelCustomer; use StoreModelProduct; $customer = new Customer('Bob'); echo $customer->getName(); $product = new Product();
When the number of imported classes grows, your code will become more verbose. So instead of importing each individual class, you can import all the classes using a single statement:
Code language: PHP (php)
use namespace{className1, className2, ...}
For example:
Code language: HTML, XML (xml)
<?php require 'src/Model/Customer.php'; require 'src/Model/Product.php'; use StoreModel{Customer, Product}; $customer = new Customer('Bob'); echo $customer->getName(); $product = new Product();
Alias classes from a namespace
First, create a new directory called Database under the project directory and place a new file Logger.php in the Database directory with the following code:
Code language: HTML, XML (xml)
<?php namespace StoreDatabase; class Logger { public function log($message) { var_dump('Log ' . $message . ' to the database.'); } }
Second, create a new directory Utils under the project directory and create a new Logger.php in the Utils directory.
Code language: HTML, XML (xml)
<?php namespace StoreUtils; class Logger { public function log($message) { var_dump('Log ' . $message); } }
Now, you have two classes with the same name in different namespaces:
Code language: plaintext (plaintext)
. ├── index.php └── src ├── Database │ └── Logger.php ├── Model │ ├── Customer.php │ └── Product.php └── Utils └── Logger.php
Third, import Logger classes from both namespaces StoreUtils and DatabaseLogger into the index.php file:
Code language: HTML, XML (xml)
<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtilsLogger; use StoreDatabaseLogger;
PHP raises the following error:
Code language: plaintext (plaintext)
Fatal error: Cannot use StoreDatabaseLogger as Logger because the name is already in use in...
To avoid this, you can just import the namespaces:
Code language: HTML, XML (xml)
<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtils; use StoreDatabase; $loggers = [ new UtilsLogger(), new DatabaseLogger() ];
Or you can give a class an alias when importing it:
Code language: JavaScript (javascript)
import namespaceclassName as newClassName;
The following example assigns the DatabaseLogger class an alias to the StoreDatabaseLogger class:
Code language: HTML, XML (xml)
<?php require 'src/Utils/Logger.php'; require 'src/Database/Logger.php'; use StoreUtilsLogger; use StoreDatabaseLogger as DatabaseLogger; $loggers = [ new Logger(), new DatabaseLogger() ];
Use classes from the global namespace
To use global classes such as built-in classes or user-defined classes without a namespace, you need to precede the name of such classes with a backslash ().
The following example shows how to use the built-in DateTime class in the App namespace:
Code language: HTML, XML (xml)
<?php namespace App; $publish_at = new DateTime(); echo $publish_at->format('Y-m-d H:i:s');
Summary
- Use a namespace to group related classes.
- Mimic the directory structure with the namespaces to make it easier to find the classes.
- Use the
useoperator to import a namespace or a class from a namespace. - Use the
askeyword to assign a namespace or a class of a namespace an alias.
Did you find this tutorial useful?
