Jump to content

Change Default Language to be None-English | Walk Trough


horst
 Share

Recommended Posts

Change Default Language to be None-English | Walk Trough

When you start a new (single) language site and the default language shouldn't be English, you can change it this way:

Go to the modules core section:

pw_change-default-language__002.thumb.jpg.bc0be0ddf0ca31082da556d88407fc54.jpg

 

Select the Language ones by the filter function:

pw_change-default-language__003.thumb.jpg.dadd7e12d2e246d0195c29220194ae47.jpg

 

We have four language related modules here, but for a single language site in none english,
we only need the base module, named "Languages Support". So go on and install it.

pw_change-default-language__004.thumb.jpg.e9fa294589eb9aab1c9d849e8fc484ef.jpg

 

After that, you can leave it, ... 

pw_change-default-language__005.thumb.jpg.da49118b6996334225125ea121a6bdba.jpg

 

... and switch to the newly created Language section under SETUP:

pw_change-default-language__006.thumb.jpg.b52c53018304d58a5524cf9814b3ce03.jpg

 

Select the default language

pw_change-default-language__008.thumb.jpg.c6ab28344d0f532feeb2b582ee093c63.jpg

 

Enter your new language name or its Shortcut and save the page.
I will use DE for a single language site in german here as example:

pw_change-default-language__009.thumb.jpg.225a124c069eb17895cf5cb05b262b3a.jpg

 

Now I go to the ProcessWire online modules directory, down to the subsection for language packs and select
and download my desired (german) one: 

pw_change-default-language__010.thumb.jpg.755b7f9644080edb9d548b348022d492.jpg

 

pw_change-default-language__011.thumb.jpg.52e550006f97070c9b4e859013f20854.jpg

 

pw_change-default-language__012.thumb.jpg.19c4883d4d2e0be7ae6cbfaf207a3557.jpg

 

pw_change-default-language__013.thumb.jpg.55f4cebc4b5c94da37d6a73dd362f664.jpg

 

After downloading a lang pack as ZIP, I go back into my SETUP > LANGUAGES > default language page in admin,
select the downloaded lang pack ZIP and install it:

pw_change-default-language__014.thumb.jpg.1f10ef4f16c17e379f386ef01e08feb8.jpg

 

pw_change-default-language__015.thumb.jpg.2fc150e3c9d1ab6c2649fd8290f26e57.jpg

 

pw_change-default-language__017.thumb.jpg.7f84b2e81f41bcdda4042af11046a048.jpg

 

 

After the ZIP is uploaded, the files are extracted and installed, most of my screen is already in
the new default language. To get all fully switched, we save and leave that page, ...

pw_change-default-language__018.thumb.jpg.a37607ae2e2da189dc0709a18d5809ac.jpg

 

... and completely logout from the admin.

pw_change-default-language__019.thumb.jpg.56d5d07b246c8e7a98fb1b58d7f36fc8.jpg

 

Now, of course, we directly login back, ...

pw_change-default-language__021.thumb.jpg.df04b91ee8ead4e6699641890a56ff68.jpg

... and see, that now also the cached parts of the admin have switched to the new default language. 🙂

pw_change-default-language__022.thumb.jpg.8002c445925f5ef1125abe3c3c8463a1.jpg

 

That was it for a single language site in none english.

 

If you want to have a multi language site, just add more languages to the SETUP > LANGUAGES section.

When using a multi language site, I think you also want to use multi language input fields, and maybe different page names for your language page pendents. If so, you need to go into MODULES > CORE > filter LANGUAGE and install what you need or want to use of it, (if not already done).

Thanks for reading and happy coding, 🙂

 

  • Like 13
  • Thanks 4
Link to comment
Share on other sites

  • horst pinned this topic
8 hours ago, kongondo said:

Excellent work @horst. Thanks for obliging and doing this 😄

 

Thanks @kongondo,

You also have a not inconsiderable share on it. You encouraged me to improve a post that was to short with a much to vague description by giving me directly a list of improvements.
So thanks for your work on this! 😉

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...
  • 9 months later...

A brilliant tutorial.

Did this with the minimal multilanguage site offered for installation. Default language is now German as wanted. 

Then I uninstalled and reinstalled English.

The main menu 'home' link is pointing to 'pw/<german homepage>, which is  as it should be, while the 'about' link points to 'pw/en/about', which should be 'pw/about'. 

In the page settings of the 'about' page the hierarchy of the DE page is 'en/about', while the hierarchy string for the EN page is '/about'. See attached screenshot.

The link of the latter is pointing to http://butoh-tanz.de/pw/about/ but clicking it we end up on http://butoh-tanz.de/pw/en/about/ 

The language menu does show both 'de' and 'en' links, as desired. But the 'en' link points to '/pw' (the processwire root, one level below site root, as this is experimental) instead of 'pw/en/'. Clicking on any link in the language menu does not change anything on any page. The 'home' page stays German while all other pages stay English. 

So obviously this method does not achieve the goal to completely reverse the language hierarchy, with all German pages having a 'pw/<pagename>' URL and all English pages having a 'pw/en/<pagename>' URL. This is absolutely no critique, as you wrote your tutorial for a single language site. 

I just would be thankful for a hint how to achieve this URL string reversal. 

 

 

image.thumb.png.372887326e01b232c3ddfbc976cab010.png

Link to comment
Share on other sites

18 minutes ago, dlen said:

So obviously this method to completely reverse the language hierarchy, with all German pages having a 'pw/<pagename>' URL and all English pages having a 'pw/en/<pagename>' URL does not work. This is no critique, as you wrote yout tutorial for a single language site. 

You can set this under Homepage > edit like shown here:

image.png.2ddf37e3fae23dea3bb335c7bd975f1a.png

Does this solve your issue?

  • Like 1
Link to comment
Share on other sites

Brilliant. Now the menu works as advertized and the page URLs reflect the respective language, i.e. '/' in the case of German, '/en/' in the case of English. 

Only the hreflang attributes in the header links are causing some headscatching:

	<link rel='alternate' hreflang='home' href='http://butoh-tanz.de/pw/' />
	<link rel='alternate' hreflang='en' href='http://butoh-tanz.de/pw/en/' />	

The second looks o.k., while the first I do not understand. Shouldn't it be 'de'?

Link to comment
Share on other sites

Sure. It is the original code fresh after installation, in _main.php:

<?php
	
	// handle output of 'hreflang' link tags for multi-language
	// this is good to do for SEO in helping search engines understand
	// what languages your site is presented in	
	foreach($languages as $language) {
		// if this page is not viewable in the language, skip it
		if(!$page->viewable($language)) continue;
		// get the http URL for this page in the given language
		$url = $page->localHttpUrl($language); 
		// hreflang code for language uses language name from homepage
		$hreflang = $homepage->getLanguageValue($language, 'name'); 
		// output the <link> tag: note that this assumes your language names are the same as required by hreflang. 
		echo "\n\t<link rel='alternate' hreflang='$hreflang' href='$url' />";
	}
	
	?>
	

I could live with that for the time being, as it is only an SEO issue, but of course it would be nice having it working.

Link to comment
Share on other sites

Please check if the name of your german language is really "de", if not, please add it. I am not talking about the de name of the homepage, but the name of the language 

Link to comment
Share on other sites

@dlen I forgot, that the name of the default language is always default and can not be changed.

Please try this updated code. BTW: where did you took that code example from?

 

<?php
	
$alternate_languages = '';
foreach ($languages as $language) {
  // if this page is not viewable in the language, skip it
  if (!$page->viewable($language)) {
    continue;
  }
  // get the http URL for this page in the given language
  $url = $page->localHttpUrl($language);
  // output the <link> tag: note that this assumes your language names are the same as required by hreflang.
  if ($language->name === 'default') {
    $alternate_languages .= "\n\t<link rel='alternate' hreflang='x-default' href='$url' />";
  }
  else{
    $alternate_languages .= "\n\t<link rel='alternate' hreflang='{$language->name}' href='$url' />";
  }
}
	echo $alternate_languages;
	?>

 

Link to comment
Share on other sites

Thx.

I used another solution, which does the job.

		foreach($languages as $language) {
			if(!$page->viewable($language)) continue;
			$url = $page->localHttpUrl($language);
			$hreflang = $homepage->getLanguageValue($language, 'name'); 
			if ($hreflang == 'home') $hreflang = 'x-Default';
			echo "\n\t<link rel='alternate' hreflang='$hreflang' href='$url' />";

The code example stems from the freshly installed multilanguage demo site.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By FireWire
      Hello community!

      I want to share a new module I've been working on that I think could be a big boost for multi-language ProcessWire sites.

      Some background, I was looking for a way for our company website to be efficiently translated as working with human translators was pretty laborious and a lack of updating content created a divergence between languages. I, and several other devs here, have talked about translation integrations and have recognized the power that DeepL has. DeepL is an AI deep learning powered service that delivers translation quality beyond any automated service available. After access to the API was opened up to the US, I built Fluency, a DeepL translation integration for ProcessWire.
      Fluency brings automated translation to every multi-language field in the admin, and also provides a translation tool allowing the user to translate their text to any language without it being inside a template's field. With Fluency you can:
      Translate any plain textarea or text input Translate any CKEditor content (yes, with markup) Translate page names for fully localized URLs on every page Translate your in-template translation function wrapped strings Translate modules Fluency is free, and now so is DeepL
      Since this module was first built DeepL has introduced free Developer accounts that allow anyone to start using Fluency at zero cost and beginning with the version 0.3.0 release Fluency now supports free DeepL accounts. As of June 2021 DeepL supports translation to 26 languages and continues to offer more!
      Installation and usage is completely plug and play. Whether you're building a new multi-language site, need to update a site to multi-language, or simply want to stop manually translating a site and make any language a one-click deal, it could not be easier to do it. Fluency works by having you match the languages configured in ProcessWIre to DeepL's. You can have your site translating to any or all of the languages DeepL translates to in minutes (quite literally).
      Let's break out the screenshots...
      When the default language tab is shown, a message is displayed to let users know that translation is available. Clicking on each tab shows a link that says "Translate from English". Clicking it shows an animated overlay with the word "Translating..." cycling through each language and a light gradient shift. Have a CKEditor field? All good. Fluency will translated it and use DeepL's ability to translate text within HTML tags. CKEditor fields can be translated as easily and accurately as text/textarea fields.

      Repeaters and AJAX created fields also have translation enabled thanks to a JavaScript MutationObserver that searches for multi-language fields and adds translation as they're inserted into the DOM. If there's a multi-language field on the page, it will have translation added.

      Same goes for image description fields. Multi-language SEO friendly images are good to go.

      Creating a new page from one of your templates? Translate your title, and also translate your page name for native language URLs. (Not available for Russian, Chinese, or Japanese languages due to URL limitations). These can be changed in the "Settings" tab for any page as well so whether you're translating new pages or existing pages, you control the URLs everywhere.

      Language configuration pages are no different. Translate the names of your languages and search for both Site Translation Files (including all of your modules)

      Translate all of the static text in your templates as well. Notice that the placeholders are retained. DeepL is pretty good at recognizing and keeping non-translatable strings like that. If it is changed, it's easy to fix manually.

      Fluency adds a "Translate" item to the CMS header. When clicked this opens up a modal with a full translation tool that lets the user translate any language to any language. No need to leave the admin if you need to translate content from a secondary language back to the default ProcessWire language. There is also a button to get the current API usage statistics. DeepL account owners can set billing limitations via character count to control costs. This may help larger sites or sites being retrofitted keep an eye on their usage. Fluency can be used by users having roles given the fluency-translate permission.

      It couldn't be easier to add Fluency to your new or existing website. Simply add your API key and you're shown what languages are currently available for translation from/to as provided by DeepL. This list and all configuration options are taken live from the API so when DeepL releases new languages you can add them to your site without any work. No module updates, just an easy configuration. Just match the language you configured in ProcessWire to the DeepL language you want it to be associated with and you're done. Fluency also allows you to create a list of words/phrases that will not be translated which can prevent items such as brands and company names from being translated when they shouldn't

       
      Limitations:
      No "translate page" - Translating multiple fields can be done by clicking multiple translation links on multiple fields at once but engineering a "one click page translate" is not feasible from a user experience standpoint. The time it takes to translate one field can be a second or two, but cumulatively that may take much longer (CKEditor fields are slower than plain text fields). There may be a workaround in the future but it isn't currently on the roadmap. No "translate site" - Same thing goes for translating an entire website at once. It would be great, but it would be a very intense process and take a very (very) long time. There may be a workaround in the future but it isn't on the roadmap. No current support for Inline CKEditor fields - Handling for CKEditor on-demand hasn't been implemented yet, this is planned for a future release though and can be done. I just forgot about it because I've never really used that feature personally.. Alpha release - This module is in alpha. Releases should be stable and usable, but there may be edge case issues. Test the module thoroughly and please report any bugs via a Github issue on the repository or respond here. Please note that the browser plugin for Grammarly conflicts with Fluency (as it does with many web applications). To address this issue it is recommended that you disable Grammarly when using Fluency, or open the admin to edit pages in a private window where Grammarly may not be loaded. This is an issue that may not have a resolution as creating a workaround may not be possible. If you have insight as to how this may be solved please visit the Github page and file a bugfix ticket.
      Requirements:
      ProcessWire  3.0+ UIKit Admin Theme That's Fluency in a nutshell. A core effort in this module is to create it so that there is nothing DeepL related hard-coded in that would require updating it when DeepL offers new languages. I would like this to be a future-friendly module that doesn't require developer work to keep it up-to-date.
      The Module Is Free
      This is my first real module and I want to give it back to the community as thanks. This is the best CMS I've worked with (thank you Ryan & contributors) and a great community (thank you dear reader).
      DeepL Developer Accounts
      In addition to paid Pro Developer accounts, DeepL now offers no-cost free accounts. Now all ProcessWire developers and users can use Fluency at no cost.
      Learn more about free and paid accounts by visiting the DeepL website. Sign up for a Developer account, get an API key, and start using Fluency today.
      Download & Feedback
      Download the latest version here
      https://github.com/SkyLundy/Fluency-Translation/archive/main.zip
      Github repository:
      https://github.com/SkyLundy/Fluency-Translation
      File issues and feature requests here (your feedback and testing is greatly appreciated):
      https://github.com/SkyLundy/Fluency-Translation/issues
       
      Thank you! ¡Gracias! Ich danke Ihnen! Merci! Obrigado! Grazie! Dank u wel! Dziękuję! Спасибо! ありがとうございます! 谢谢你!

    • By daniel_puehringer
      Hi community,

      I am using the "PageTable" Module (also called "ProFields: Page Table") and the built in "Language" Module (also called "Languages Support").

      With the help of PageTable I was able to create several content elements which should usually be displayed in German(default language) and English.

      However some Content Elements should only be shown in German and NOT in English.

      Well sounds easy, right? Not so fast. I really love this CMS, but I have not found a solution for this problem yet.
      As you can see in the screenshots attached I tried to uncheck the "active" Checkbox for the english language to completely hide the content element for english users.

      However no matter what I do the german text shows on the english page.
      If I leave the "content-should-not-be-shown-in-english"(see Screenshot Number 2) blank and save the page, the page will inherit the german page url "content-element-with-simple-text-which-should-only-be-shown-in-german".

      My question therefore is:
      How can I hide a specific content-element for only one language?

      I´m using the latest processwire & module versions.

      The code which I use to render the content elements looks like this:
      //Info: contentelements is a field of type "ProFields: Page Table" <?php foreach ($page->contentelements as $element): echo($element->render()); endforeach; ?> filename: basic-page.php


      I would really appreciate your help since I haven´t found a solution after reading through quite a lot of forum posts.

      All the best,
      Dani


    • By joeck
      I am struggling with an issue where my language switcher with flags sometimes doesn't show the flag.
      It works in the default language (german):

      but when the site is in english the german flag is not shown (path to image is not found):

      I don't really understand why it works if the site is shown in german but not in english..
      Code for language switcher:
      // remember what language is set to $savedLanguage = $user->language; $languageImage = $savedLanguage->image->url; echo "<li><a href='#' class='dropdown-toggle' data-toggle='dropdown'><img src='$languageImage' alt='$savedLanguage->title'> <span uk-icon='icon: chevron-down'></span></a>"; echo "<div class='uk-navbar-dropdown'>"; echo " <ul class='uk-nav uk-navbar-dropdown-nav'>"; foreach($languages as $language) { //go through all languages // if user is already viewing the page in this language, skip it if($language->id == $savedLanguage->id) continue; // if this page isn't viewable (active) for the language, display root page $viewable = true; if(!$page->viewable($language)) $viewable = false; // set the user's language, so that the $page->url and any other // fields we access from it will be reflective of the $language $user->language = $language; // output a link to this page in the other language $path = $language->image->url; $pagePath = $page->url; if(!$viewable) $pagePath = $pages->get(1)->url; echo "<li><a class='uk-text-medium' href='$pagePath' alt='$language->title'><img src='$path' alt='$language->title flag'> $language->title</a></li>"; } echo " </ul>"; echo "</div>"; echo "</li>"; // restore the original language setting $user->language = $savedLanguage; Language template:

      image field is configured as automatic (array if multiple)
      in language page (both german and english) only one image is saved
      html output of language switcher dropwon (image couldn't be loaded):

      html output when image can be displayed:

    • By MoritzLost
      I've seen a couple of questions regarding namespaces and autoloading floating around the forum recently, so I decided to write a little tutorial. In general, I often see people getting confused when they try to wrap their head around namespaces, autoloading, Composer and the mapping of namespaces to directory structures all at once. In fact, those are very much independent, distinct concepts, and it is much easier to explain and understand them separately. So this guide is structured as follows:
      How namespaces work in PHP. How autoloading works in PHP. Conventions for mapping namespaces to directory structures: PSR-4. How autoloading works in Composer and ProcessWire's class loader. How to use the class loader in a ProcessWire module. Feel free to skip the sections you're already familiar with.
      Namespaces in PHP
      The purpose of namespaces in PHP is to avoid naming conflicts between classes, functions and constants, especially when you're using external libraries and frameworks. Nothing more. It's important to understand that this has nothing at all to do with autoloading, directory structures or file names. You can put namespaced stuff everywhere you want. You can even have multiple namespaces inside a single file (don't try this at home). Namespaces only exist to be able to use a generic name – for example, ProcessWire's Config class – multiple times in different contexts without getting a naming conflict. Without namespaces, I couldn't use any library that includes a Config class of it's own, because that name is already taken. With namespaces, you can have a distinction between the classes ProcessWire\Config and MoritzLost\Config. You can also use sub-namespaces to further segregate your code into logical groups. For example, I can have two classes MoritzLost\Frontend\Config and MoritzLost\Backend\Config– a class name only needs to be unique within it's namespace.
      You can declare the namespace for a PHP file using the namespace statement at the top:
      // file-one.php <?php namespace ProcessWire; // file-two.php <?php namespace MoritzLost\Frontend; This way, all classes, methods and constants defined inside this file are placed in that namespace. All ProcessWire classes live in the ProcessWire namespace.
      Now to use one of those classes – for example, to instantiate it – you have a couple of options. You can either use it's fully qualified class name or import it into the current namespace. Also, if you are inside a namespaced file, any reference to a class is relative to that namespace. Unless it starts with a backward slash, in this case it's relative to the global namespace. So all of those examples are equivalent:
      // example-one.php <?php namespace ProcessWire; $page = new Page(); // example-two.php <?php use ProcessWire\Page; $page = new Page(); // example-three.php <?php $page = new ProcessWire\Page(); // example-four.php <?php namespace MoritzLost\Somewhere\Over\The\Rainbow; $page = new \ProcessWire\Page(); The use statement in the second example can be read like this: “Inside this file, all references to Page refer to the class \ProcessWire\Page”
      How autoloading works
      Every PHP program starts with one entry file – for ProcessWire, that's usually it's index.php. But you don't want to keep all your code in one file, that would get out of hand quickly. Once you start to split your code into several individual files however, you have to take care of manually including them with require or include calls. That becomes very tedious as well. The purpose of autoloading is to be able to add new code in new files without having to import them manually. This, again, has nothing to do with namespaces, not even something with file locations. Autoloading is a pretty simple concept: If you try to use a class that hasn't been loaded yet, PHP calls upon it's registered autoloaders as a last-ditch attempt to load them before throwing an exception.
      Let's look at a simple example:
      // classes.php <?php class A { /** class stuff */ } class B { /** class stuff */ } // index.php <?php spl_autoload_register(function ($class) { include_once 'classes.php'; }); new A(); new B(); This is a complete and functional autoloader. If you don't believe me, go ahead and save those two files (classes.php and index.php) and run the index.php with php -f index.php. Then comment out the include_once call and run it again, then you'll get an error that class A was not found.
      Now here's what happens when index.php is executed (with the autoloader active):
      Our anonymous function is added to the autoload queue through spl_autoload_register. PHP tries to instantiate class A, but can't because it's not loaded yet. If there was no autoloader registered, the program would die with a fatal error at this point. But since there is an autoloader ... The autoloader is called. Our autoloader includes classes.php with the class definition. That was a close one! Since the class has been loaded, execution goes back to the index.php which can now proceed to instantiate A and B. If the class was still not loaded at this point, PHP would go back to the original plan and die. One thing to note is that the autoloader will only be called once in this example. That's because both A and B are in the same file and that file is included during the first call to the autoloader. Autoloading works on files, not on classes!
      The important takeaway is that PHP doesn't know if the autoloader knows where to find the class it asks for or, if there are multiple autoloader, which one can load it. PHP just calls each registered autoloader in turn and checks if the class has been loaded after each one. If the class still isn't loaded after the last autoloader is done, it's error time.
      What the autoloader actually does is pretty much wild wild west as well. It takes the name of the class PHP is trying to load as an argument, but it doesn't have to do anything with it. Our autoloader ignores it entirely. Instead, it just includes classes.php and says to itself “My job here is done”. If class A was in another file, it wouldn't have worked.
      This process has two main advantages:
      Since autoloaders are only called on-demand to load classes just in time, we only include the files we actually need. If in the example above class A and B are not used in some scenarios, the classes.php will not be included, which will result in better performance for larger projects (though this isn't as cut and dry, since autoloading has it's own overhead, so if you load most classes anyway during a single request, it will actually be less efficient). If the autoloader is smart enough to somehow map class names to the files they're located in, we can just let the autoloader handle including the classes we need, without having to worry about jamming include statements everywhere. That brings us to ... PSR-4, namespaces and directory structures
      As you see, namespaces and autoloading are both pretty limited concepts. And they aren't inherently linked to each other. You can namespace your classes without ever adding an autoloader, and you can autoload classes that are all in the same namespace. But they become useful when you put them together. At the core of all that autoloading talk is a simple idea: By putting classes in files named after their class names, and putting those files in directory hierarchies based on the namespace hierarchy, the autoloader can efficiently find and load those files based on the namespace. All it needs is a list of root namespaces with their corresponding directories.
      The exact way class names and namespaces are mapped to directory structures and file names is purely conventional. The accepted convention for this is PSR-4. This is a super simple standard which basically just sums up the ideas above:
      A base namespace is mapped to a specific directory in the file system. When the autoloader is asked to load a class in that namespace (or a sub-namespace of it), it starts looking in that folder. This "base" namespace may include multiple parts – for example, I could use MoritzLost\MyAwesomeLibrary as a base and map that to my source directory. PSR-4 calls this a "namespace prefix". Each sub-namespace corresponds to a sub-directory. So by looking at the namespace, you can follow subdirectories to the location where you expect to find the class file. Finally, the class name is mapped directly to the file name. So MyCoolClass needs to be put inside MyCoolClass.php. This all sounds simple and straightforward - and it absolutely is! It's only once you mash everything together, mix up language features, accepted conventions and proprietary implementations like Composer on top that it becomes hard to grasp in one go.
      Composer and ProcessWire's class loader
      Now all that's left is to talk about how Composer and ProcessWire provide autoloading.
      Composer, of course, is primarily a tool for dependency management. But because most libraries use namespaces and most developers want to have the libraries they're using autoloaded, those topics become a prerequisite to understanding what Composer does in this regard. Composer can use different autoloading mechanisms; for example, you can just give it a static list of files to include for every request, or use the older PSR-0 standard. But most modern libraries use PSR-4 to autoload classes. So all Composer needs to function is a mapping of namespace prefixes to directories. Each library maintains this mapping for it's PSR-4-structured classes through the autoload information in their composer.json. You can do this for your own site to: Just include the autoload information as shown in the documentation and point it to the directory of your class files.
      Composer collects all that information and uses it to generate a custom file at vendor/autoload.php — that's the one you need to include somewhere whenever you set up Composer in one of your projects. Bells and whistles aside, this file just registers an autoloader function that will use all the information collected from your own and your included libraries' composer.json to locate and include class files on demand.
      You can read more about how to optimize Composer's autoloader for production usage here. If you want to read up on how to set up Composer for your own sites, read my ProcessWire + Composer integration guide instead.
      And finally, what does ProcessWire do to handle all this? Turns out, ProcessWire has it's own autoloader implementation that is more or less PSR-4 compliant. You can access it as an API variable ($classLoader or wire('classLoader'), depending on context). Instead of using a static configuration file like Composer, the namespace -> directory mapping is added during the runtime by calling $classLoader->addNamespace. As you would expect, this function accepts a namespace and a directory path. You can use this to register your own custom namespaces. Alternatively, if you have site-specific classes within the ProcessWire namespace, you can just add their location to the class loader using the same method: $classLoader->addNamespace('ProcessWire', '/path/to/your/classes/').
      Utilizing custom namespaces and autoloading in ProcessWire modules
      Now as a final remark, I wanted to give an example of how to use custom namespaces and the class loader in your own modules. I'll use my TrelloWire module as an example:
      Decide what namespace you're going to use. The main module file should live in the ProcessWire namespace, but if you have other classes in your module, they can and should use a custom namespace to avoid collisions with other modules. TrelloWire uses ProcessWire\TrelloWire, but you can also use something outside the ProcessWire namespace. You need to make sure to add the namespace to the class loader as early as possible. If either you or a user of your module tries to instantiate one of your custom classes before that, it will fail. Good places to start are the constructor of your main module file, or their init or ready methods. Here's a complete example. The module uses only one custom namespaced class: ProcessWire\TrelloWire\TrelloWireApi, located in the src/ directory of the module. But with this setup, I can add more classes whenever I need without having to modify anything else.
      /** * The constructor registers the TrelloWire namespace used by this module. */ public function __construct() { $namespace = 'ProcessWire\\TrelloWire'; $classLoader = $this->wire('classLoader'); if (!$classLoader->hasNamespace($namespace)) { $srcPath = $this->wire('config')->paths->get($this) . 'src/'; $classLoader->addNamespace($namespace, $srcPath); } } Source
      Thanks for making it through to the very end! I gotta learn to keep those things short. Anyway, I hope this clears up some questions about namespaces and autoloading. Let me know if I got something wrong, and feel free to add your own tips and tricks!
    • By snobjorn
      Here's my Norwegian language pack for ProcessWire. I've been adding translations gradually since 2015. By November 2020 the translations are completed, and up to date with the latest dev version of ProcessWire.
      For details, go to the ProcessWire Modules page …
      https://modules.processwire.com/modules/norwegian/
      … and/or GitHub:
      https://github.com/snobjorn/processwire-norwegian-language-pack-nb-no
      Status:
      Completed / up to date.
      Third party and PRO module translations have moved to another repository:
      The site files have been moved to a new repository for module files in Norwegian. Those translations includes translations for some free and some pro modules, see the complete list at GitHub.
×
×
  • Create New...